electron分享之进程间的通信 | 8月更文挑战

1,099 阅读2分钟

1、主进程与渲染进程间通过IPC进行通信,例如:

主进程

const { ipcMain } = require('electron') 
// 监听渲染进程信息
ipcMain.on('message', (event, arg) => {
  console.log('ping')
  event.sender.send('message-reply', 'pong') // 回复子程序
})
// 主进程单独往渲染进程发信息
win.webContents.send('message-reply', 'pong')

ipcMain.handle('perform-action', (event, ...args) => {
  // ... 代表渲染器操作
})

渲染进程

const { ipcRenderer } = require('electron')
ipcRenderer.send('message', 'ping') // 发送给主进程
ipcRenderer.on('message-reply', (event, arg) => {
  console.log(arg) // pong
}

//渲染进程中调用主进程方法
ipcRenderer.invoke('perform-action', ...args)

2、使用remote模块 -->只能在渲染进程中去调用主进程的模块
实现原理:类似于 Java 中的 RMI,底层基于IPC

const { BrowserWindow ...(主进程的API模块) } = require('electron').remote

注:因为electron基于node开发的,node的模块化是commonjs(require)规范,与esm(import - es6)有所不同
解决方法:使用webpack打包

electron快捷键开发 这里使用的是electron的原生方法。当然也可以使用第三方JS库,如mousetrap等。

  1. 主进程中监听键盘事件
  //1、本地快捷键 -->利用menu模块的accelerator属性 必须当应用获取焦点时才能被触发
  const { Menu, MenuItem } = require('electron')  --commnJS规范

  const menu = new Menu()
  menu.append(new MenuItem({
    label: 'Electron',
    submenu: [{
      role: 'help',
      accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
      click: () => { console.log('Electron rocks!') }
    }]
  }))

  Menu.setApplicationMenu(menu)

  //2、全局快捷键  监听键盘事件,无论应用是否获取焦点,都会被触发
  app.on('ready', function () {
    //注册
    globalShortcut.register('CommandOrControl+Alt+K', function () {
      dialog.showMessageBox({
        type: 'info',
        message: '成功!',
        detail: '你按下了一个全局注册的快捷键绑定.',
        buttons: ['好的']
      })
    })
  })
  
  app.on('will-quit', function () {
    //注销所有快捷键
    globalShortcut.unregisterAll()
  })
  1. 渲染进程中监听键盘事件
//1、使用浏览窗口监听键盘事件 需要自行判断什么键按下
e.g.
window.addEventListener('keyup', doSomething, true)
true,这意味着当前监听器总是在其他监听器之前接收按键,以避免其它监听器调用 stopPropagation()。

//2、使用第三方库 mousetrap(推荐)