Skip to content

键盘快捷键

该功能允许你为 Electron 应用程序配置应用和全局键盘快捷键。

示例

本地快捷键

应用键盘快捷键仅在应用程序被聚焦时触发。 为了配置本地快捷键,你需要在创建Menu模块中的MenuItem时指定accelerator属性。

Example

const { app, BrowserWindow, Menu, MenuItem } = require('electron/main')

function createWindow () {
    const win = new BrowserWindow({
        width: 800,
        height: 600
    })

    win.loadFile('index.html')
}

const menu = new Menu()
menu.append(new MenuItem({
    label: 'Electron',
    submenu: [{
        role: 'help',
        accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
        click: () => { console.log('Electron rocks!') }
    }]
}))

Menu.setApplicationMenu(menu)

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>键盘快捷键</title>
</head>

<body>
    <h1>键盘快捷键</h1>
    <p>在windows中按Alt+Shift+I 或 在mac中按Opt+Cmd+I打开控制台查看输出信息</p>
</body>

</html>

全局快捷键

要配置全局键盘快捷键, 您需要使用 globalShortcon 模块来检测键盘事件,即使应用程序没有获得键盘焦点。

Example

const { app, BrowserWindow, globalShortcut } = require('electron/main')

function createWindow () {
    const win = new BrowserWindow({
        width: 800,
        height: 600
    })

    win.loadFile('index.html')
}

app.whenReady().then(() => {
    globalShortcut.register('Alt+CommandOrControl+I', () => {
        console.log('Electron loves global shortcuts!')
    })
}).then(createWindow)

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>全局快捷键</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>全局快捷键</h1>
    <p>在Windows上按Alt+Ctrl+I,在Mac上按Opt+Cmd+I,可以看到打印到控制台的消息。</p>
</body>
</html>

在浏览器窗口内的快捷方式

使用 web APIs

如果您想要在 BrowserWindow 中处理键盘快捷键,你可以在渲染进程中使用 addEventListener() API来监听 kepup 和 keydown DOM事件。

Example

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron/main')

function createWindow () {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600
    })

    // and load the index.html of the app.
    mainWindow.loadFile('index.html')
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
    createWindow()

    app.on('activate', function () {
        // On macOS it's common to re-create a window in the app when the
        // dock icon is clicked and there are no other windows open.
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
</head>
<body>
    <h1>Hello World!</h1>

    <p>Hit any key with this window focused to see it captured here.</p>
    <div><span>Last Key Pressed: </span><span id="last-keypress"></span></div>
    <script src="./renderer.js"></script>
</body>
</html>
function handleKeyPress (event) {
    // You can put code here to handle the keypress.
    document.getElementById('last-keypress').innerText = event.key
    console.log(`You pressed ${event.key}`)
}

window.addEventListener('keyup', handleKeyPress, true)

拦截主进程中的事件

在调度页面中的keydown和keyup事件之前,会发出before-input-event事件。 它可以用于捕获和处理在菜单中不可见的自定义快捷方式。

Example

const { app, BrowserWindow } = require('electron/main')

app.whenReady().then(() => {
    const win = new BrowserWindow({ width: 800, height: 600 })

    win.loadFile('index.html')
    win.webContents.on('before-input-event', (event, input) => {
        if (input.control && input.key.toLowerCase() === 'i') {
        console.log('Pressed Control+I')
        event.preventDefault()
        }
    })
})
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello World!</h1>
    <p>Hit Ctrl+I to see a message printed to the console.</p>
</body>
</html>

在运行Electron应用程序之后,如果你打开你运行Electron应用的终端并按下 Ctrl+I 组合键,你会发现刚才按下的组合键被成功拦截了。

使用第三方库

如果您不想手动进行快捷键解析,可以使用一些库来进行高级的按键检测。例如 mousetrap. 以下是在渲染进程中 mousetrap 的使用示例:

Mousetrap.bind('4', () => { console.log('4') })
Mousetrap.bind('?', () => { console.log('show shortcuts!') })
Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')

// combinations
Mousetrap.bind('command+shift+k', () => { console.log('command shift k') })

// map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], () => {
    console.log('command k or control k')

    // return false to prevent default behavior and stop event from bubbling
    return false
})

// gmail style sequences
Mousetrap.bind('g i', () => { console.log('go to inbox') })
Mousetrap.bind('* a', () => { console.log('select all') })

// konami code!
Mousetrap.bind('up up down down left right left right b a enter', () => {
    console.log('konami code')
})