我们通常会记住我们每天在PC上使用的所有应用程序的某些快捷方式.为了使您的应用程序直观且易于用户访问,您必须允许用户使用快捷方式.
我们将使用globalShortcut模块在我们的应用程序中定义快捷方式.请注意,加速器是可以包含多个修饰符和键代码的字符串,由+字符组合.这些加速器用于在我们的应用程序中定义键盘快捷键.
让我们考虑一个示例并创建一个快捷方式.为此,我们将按照对话框示例,我们使用打开的对话框打开文件.我们将注册 CommandOrControl + O 快捷方式以显示对话框.
我们的 main.js 代码将保持不变之前.因此,创建一个新的 main.js 文件并在其中输入以下代码 :
const {app, BrowserWindow} = require('electron')const url = require('url')const path = require('path')const {ipcMain} = require('electron')let winfunction createWindow() { win = new BrowserWindow({width: 800, height: 600}) win.loadURL(url.format ({ pathname: path.join(__dirname, 'index.html'), 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 时打开.
现在创建一个新的 index.html 文件以下内容 :
File read using system dialogs Press CTRL/CMD + O to open a file.
我们注册了一个新的快捷方式并传递了一个回调,只要我们按下这个快捷方式就会执行回调.我们可以在不需要时取消注册快捷方式.
现在,一旦应用程序打开,我们将使用我们刚刚定义的快捷方式获取打开文件的消息.
这些快捷方式可以通过允许用户选择自己的方式进行定制已定义操作的快捷方式.