Electron中通過globalShortcut實現監聽鍵盤事件進而實現快捷鍵功能

場景

用HTML和CSS和JS構建跨平臺桌面應用程序的開源庫Electron的介紹以及搭建HelloWorld:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106413828

Electron怎樣進行渲染進程調試和使用瀏覽器和VSCode進行調試:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/106414541

在上面搭建好項目以及知道怎樣進行調試後,那麼Electron怎樣實現系統快捷鍵。

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公衆號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

主進程實現鍵盤快捷鍵

globalShortcut模塊可以向操作系統註冊/註銷全局鍵盤快捷方式,以便您可以自定義各種快捷方式的操作。

注:快捷方式是全局的,即使應用程序沒有鍵盤焦點,它也能工作。

打開項目的main.js

引入globalShortcut模塊

const {app, BrowserWindow,globalShortcut} = require('electron')

然後找到app.whenReady事件,將其修改爲如下

app.whenReady().then(() => {
  createWindow();
  //註冊Ctr+x事件
  const ret = globalShortcut.register('CommandOrControl+X', () => {
    console.log('CommandOrControl+X is pressed')
  })

  if (!ret) {
    console.log('registration failed')
  }

  // 驗證是否註冊成功
  console.log(globalShortcut.isRegistered('CommandOrControl+X'))
  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()
  })
})

注:

首先通過globalShortcut.register註冊ctrl+x的快捷鍵,然後通過globalShortcut.isRegistered獲取是否註冊成功快捷鍵。

然後再要在窗體關閉的事件中取消註冊,同樣在main.js中找到app.on('window-all-closed'

將其修改爲

// Quit when all windows are closed.
app.on('window-all-closed', function () {
// Unregister a shortcut.
globalShortcut.unregister('CommandOrControl+X')

// Unregister all shortcuts.
globalShortcut.unregisterAll()
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

調試運行項目,點擊快捷鍵ctrl+x,查看調試控制檯輸出

 

渲染進程快捷鍵

在渲染進程中實現快捷鍵,打開renderer.js

引入remote模塊

const {remote} = require("electron");

然後通過remote調用globalShortcut

remote.globalShortcut.register("CommandOrControl+G",()=>{
  console.log("您按下了ctrl + G");
})

運行項目打開調試頁面,按下快捷鍵ctrl+G

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章