キーボード ショート カット
Accelerators
Accelerators are strings that can be used to represent keyboard shortcuts throughout your Electron. These strings can contain multiple modifiers keys and a single key code joined by the +
character.
[!NOTE] Accelerators are case-insensitive.
利用可能な修飾キー
Command
(または略してCmd
)Control
(または略してCtrl
)CommandOrControl
(または略してCmdOrCtrl
)Alt
Option
AltGr
Shift
Super
(orMeta
as alias)
利用可能なキーコード
0
から9
A
からZ
F1
からF24
- 様々な記号:
)
,!
,@
,#
,$
,%
,^
,&
,*
,(
,:
,;
,:
,+
,=
,<
,,
,_
,-
,>
,.
,?
,/
,~
,`
,{
,]
,[
,|
,\
,}
,"
Plus
Space
Tab
Capslock
Numlock
スクロールロック
Backspace
削除
Insert
Return
(またはエイリアスとしてEnter
)Up
とDown
、Left
、Right
Home
とEnd
PageUp
とPageDown
Escape
(または略してEsc
)VolumeUp
とVolumeDown
、VolumeMute
MediaNextTrack
とMediaPreviousTrack
、MediaStop
、MediaPlayPause
PrintScreen
- NumPad Keys
num0
からnum9
numdec
- 数字キーnumadd
- テンキーの+
キーnumsub
- テンキーの-
キーnummult
- テンキーの*
キーnumdiv
- テンキーの÷
キー
Cross-platform modifiers
Many modifier accelerators map to different keys between operating systems.
Modifier | macOS | Windows、Linux |
---|---|---|
CommandOrControl | Command (⌘) | 管理 |
Command | Command (⌘) | なし |
管理 | Control (^) | 管理 |
Alt | Option (⌥) | Alt |
Option | Option (⌥) | なし |
Super (Meta ) | Command (⌘) | Windows (⊞) |
- On Linux and Windows, the
Command
modifier does not have any effect. In general, you should use theCommandOrControl
modifier instead, which represents ⌘ Cmd on macOS and Ctrl on Linux and Windows. Option
ではなくAlt
を使用してください。 The ⌥ Opt key only exists on macOS, whereas theAlt
will map to the appropriate modifier on all platforms.
サンプル
Here are some examples of cross-platform Electron accelerators for common editing operations:
- Copy:
CommandOrControl+C
- Paste:
CommandOrControl+V
- Undo:
CommandOrControl+Z
- Redo:
CommandOrControl+Shift+Z
Local shortcuts
Local keyboard shortcuts are triggered only when the application is focused. These shortcuts map to specific menu items within the app's main application menu.
To define a local keyboard shortcut, you need to configure the accelerator
property when creating a MenuItem. Then, the click
event associated to that menu item will trigger upon using that accelerator.
const { dialog, Menu, MenuItem } = require('electron/main')
const menu = new Menu()
// The first submenu needs to be the app menu on macOS
if (process.platform === 'darwin') {
const appMenu = new MenuItem({ role: 'appMenu' })
menu.append(appMenu)
}
const submenu = Menu.buildFromTemplate([{
label: 'Open a Dialog',
click: () => dialog.showMessageBox({ message: 'Hello World!' }),
accelerator: 'CommandOrControl+Alt+R'
}])
menu.append(new MenuItem({ label: 'Custom Menu', submenu }))
Menu.setApplicationMenu(menu)
In the above example, a native "Hello World" dialog will open when pressing ⌘ Cmd+⌥ Opt+R on macOS or Ctrl+Alt+R on other platforms.
[!TIP] Accelerators can work even when menu items are hidden. On macOS, this feature can be disabled by setting
acceleratorWorksWhenHidden: false
when building aMenuItem
.
[!TIP] On Windows and Linux, the
registerAccelerator
property of theMenuItem
can be set tofalse
so that the accelerator is visible in the system menu but not enabled.
Global shortcuts
Global keyboard shortcuts work even when your app is out of focus. To configure a global keyboard shortcut, you can use the globalShortcut.register
function to specify shortcuts.
const { dialog, globalShortcut } = require('electron/main')
globalShortcut.register('CommandOrControl+Alt+R', () => {
dialog.showMessageBox({ message: 'Hello World!' })
})
To later unregister a shortcut, you can use the globalShortcut.unregisterAccelerator
function.
const { globalShortcut } = require('electron/main')
globalShortcut.unregister('CommandOrControl+Alt+R')
[!WARNING] On macOS, there's a long-standing bug with
globalShortcut
that prevents it from working with keyboard layouts other than QWERTY (electron/electron#19747).
Shortcuts within a window
In the renderer process
If you want to handle keyboard shortcuts within a BaseWindow, you can listen for the keyup
and keydown
DOM Events inside the renderer process using the addEventListener API.
- main.js
- index.html
- renderer.js
// 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">
<!-- http://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)
[!NOTE] The third parameter
true
indicates that the listener will always receive key presses before other listeners so they can't havestopPropagation()
called on them.
メインプロセス内でのイベントの受け取り
The before-input-event
event is emitted before dispatching keydown
and keyup
events in the renderer process. メニューに表示されないカスタムショートカットをキャッチして処理するため使用することができます。
const { app, BrowserWindow } = require('electron/main')
app.whenReady().then(() => {
const win = new BrowserWindow()
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()
}
})
})