Electron - 定義快捷鍵



我們通常會記住我們在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 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)

這段程式碼將在我們的主程序從渲染程序接收 'openFile' 訊息時彈出開啟對話方塊。之前,這個對話方塊在應用程式執行時彈出。現在讓我們將其限制為僅在按下 **CommandOrControl+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>

我們註冊了一個新的快捷鍵,並傳遞了一個回撥函式,每當我們按下此快捷鍵時都會執行該回調函式。我們可以根據需要登出快捷鍵。

現在,一旦應用程式開啟,我們將收到使用我們剛剛定義的快捷鍵開啟檔案的提示。

Open dialog

可以透過允許使用者為已定義的操作選擇他自己的快捷鍵來使這些快捷鍵可自定義。

廣告