Electron-defining-shortcuts
Electron-ショートカットの定義
通常、PCで毎日使用するすべてのアプリの特定のショートカットを記憶しています。 ユーザーが直感的で簡単にアクセスできるようにアプリケーションを作成するには、ユーザーがショートカットを使用できるようにする必要があります。
globalShortcutモジュールを使用して、アプリのショートカットを定義します。 Accelerators は、+文字で結合された複数の修飾子とキーコードを含むことができる文字列であることに注意してください。 これらのアクセラレータは、アプリケーション全体でキーボードショートカットを定義するために使用されます。
例を考えて、ショートカットを作成しましょう。 このため、ファイルを開くために開いたダイアログボックスを使用したダイアログボックスの例に従います。 CommandOrControl + O ショートカットを登録して、ダイアログボックスを表示します。
*main.js* コードは以前と同じままです。 新しい *main.js* ファイルを作成し、その中に次のコードを入力してください-
const {app, BrowserWindow} = require('electron')
const url = require('url')
const path = require('path')
const {ipcMain} = require('electron')
let win
function createWindow() {
win = new BrowserWindow({width: 800, height: 600})
win.loadURL(url.format ({
pathname: path.join(__dirname, 'indexl'),
protocol: 'file:',
slashes: true
}))
}
ipcMain.on('openFile', (event, path) => {
const {dialog} = require('electron')
const fs = require('fs')
dialog.showOpenDialog(function (fileNames) {
//fileNames is an array that contains all the selected
if(fileNames === undefined)
console.log("No file selected")
else
readFile(fileNames[0])
})
function readFile(filepath){
fs.readFile(filepath, 'utf-8', (err, data) => {
if(err){
alert("An error ocurred reading the file :" + err.message)
return
}
//handle the file content
event.sender.send('fileData', data)
})
}
})
app.on('ready', createWindow)
このコードは、メインプロセスがレンダラープロセスから「openFile」メッセージを受け取るたびに、開いているダイアログボックスをポップします。 以前、このダイアログボックスは、アプリが実行されるたびにポップアップ表示されました。 CommandOrControl + O を押したときにのみ開くように制限しましょう。
ここで、次の内容で新しい indexl ファイルを作成します-
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>File read using system dialogs</title>
</head>
<body>
<p>Press CTRL/CMD + O to open a file. </p>
<script type = "text/javascript">
const {ipcRenderer, remote} = require('electron')
const {globalShortcut} = remote
globalShortcut.register('CommandOrControl+O', () => {
ipcRenderer.send('openFile', () => {
console.log("Event sent.");
})
ipcRenderer.on('fileData', (event, data) => {
document.write(data)
})
})
</script>
</body>
</html>
新しいショートカットを登録し、このショートカットを押すたびに実行されるコールバックを渡しました。 ショートカットは、必要に応じて登録解除できます。
これで、アプリを開くと、先ほど定義したショートカットを使用してファイルを開くようメッセージが表示されます。
これらのショートカットは、ユーザーが定義済みのアクションに対して独自のショートカットを選択できるようにすることで、カスタマイズ可能にすることができます。