場景:在消息發送的輸入框中,使用快捷鍵的復制粘貼,全選,等等都會失效。
解決方案如下:
將如下代碼放到main/index.js主進程中
mainWIndow = new BrowserWindow({});
if (process.platform === 'darwin') { let contents = mainWindow.webContents globalShortcut.register('CommandOrControl+C', () => { contents.copy() }) globalShortcut.register('CommandOrControl+V', () => { contents.paste() }) globalShortcut.register('CommandOrControl+X', () => { contents.cut() }) globalShortcut.register('CommandOrControl+A', () => { contents.selectAll() }) }
補充:在實踐了上述方案,發現一個后續的問題,electron項目的快捷鍵可以使用了,但是一個更嚴重的問題是,系統本身的快捷鍵由於被electron全局注冊,因此系統的快捷鍵失效。
面臨這個問題的解決辦法,我們進行以下方法修復
mainWindow.on('focus', () => { // mac下快捷鍵失效的問題 if (process.platform === 'darwin') { let contents = mainWindow.webContents globalShortcut.register('CommandOrControl+C', () => { console.log('注冊復制快捷鍵成功') contents.copy() }) globalShortcut.register('CommandOrControl+V', () => { console.log('注冊粘貼快捷鍵成功') contents.paste() }) globalShortcut.register('CommandOrControl+X', () => { console.log('注冊剪切快捷鍵成功') contents.cut() }) globalShortcut.register('CommandOrControl+A', () => { console.log('注冊全選快捷鍵成功') contents.selectAll() }) } }) mainWindow.on('blur', () => { globalShortcut.unregisterAll() // 注銷鍵盤事件 })
思路:在窗口獲取焦點的時候注冊快捷鍵,在窗口失去焦點的時候注銷electron的快捷鍵即可。