日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Electron中通过globalShortcut实现监听键盘事件进而实现快捷键功能

發布時間:2025/3/19 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 + Qif (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

?

?

總結

以上是生活随笔為你收集整理的Electron中通过globalShortcut实现监听键盘事件进而实现快捷键功能的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。