开发学院

您的位置:首页>教程>正文

教程正文

Electron 教程:定义快捷键

  用户通常会记住每天在电脑上使用所有程序的快捷键。为了让您的应用程序对用户来说感觉直观且易于访问,开发者应该允许用户创建快捷键访问程序。本文我们将使用globalShortcut模块在我们的Electron程序中定义快捷键。

  让我们通过一个例子,创建快捷键。为此,我们将遵循使用打开对话框打开文件的对话框示例。我们将注册一个Command/Control+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, '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)

  每当我们的主进程从渲染器进程接收到“打开文件”消息时,这段代码就会弹出打开对话框。此前,每当应用程序运行时,都会弹出此对话框。现在让我们限制它只在我们按下Command/Control+O时打开.

  现在用以下内容创建一个新的index.html文件

<!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>

  我们注册了一个新的快捷键,并传递了一个回调函数,每当我们按下这个快捷键组合时都会执行这个函数。当我们不需要快捷键时,我们可以取消它们的注册。

  现在,一旦打开应用程序,我们将获得使用我们刚刚定义的快捷键打开文件的消息。

opendialog.jpg

  这些快捷键可以通过允许用户为定义的操作选择自己的快捷键来定制。