electron实现托盘右键菜单和进程间的ipc通信

忙活了几天,终于把自己的播放器做出个样子了,看看效果

播放器效果


想做桌面应用但是下载包不成功的可以去看看我之前打包详细过程
electron生成桌面应用程序
之前实现最小化最大化和退去使用了渲染进程向主进程发起通信
vite+vue3+electron踩坑记录ipcRenderer通信,vue-router打包白屏问题
现在为了实现托盘右键菜单的停止和播放及上一首下一首的功能需要主进程向渲染进程发起通信,使用webContents
webContents 是一个事件发出者.它负责渲染并控制网页,也是 BrowserWindow 对象的属性
webContents.send(channel[, arg1][, arg2][, …])
通过 channel 发送异步消息给渲染进程,你也可发送任意的参数.参数应该在 JSON 内部序列化,并且此后没有函数或原形链被包括了.
渲染进程可以通过使用 ipcRenderer 监听 channel 来处理消息.

let win = new BrowserWindow({
    width: 1200,
    height: 900,
    minWidth: 800,
    minHeight: 600,
    transparent: true,
    webPreferences: {
      nodeIntegration: true, // 允许在页面中使用节点js
      contextIsolation: true, // 启用上下文隔离
      enableRemoteModule: true, // 允许使用 remote 模块
      preload: path.join(__dirname, "preload.js")
    },
    frame: false,
  });
  const contextMenu = [
    { label: '播放/暂停', click:()=>{win.webContents.send('pauseOrPlay')} },
    { label: '上一首', click:()=>{win.webContents.send('next', -1);} },
    { label: '下一首', click:()=>{win.webContents.send('next', 1);} },
    {type: "separator"},
    { label: '播放方式', submenu:[
      { label: `顺序播放`, click:()=>{win.webContents.send('setplayState',0);updateTrayMenu(0)}},
      { label: '随机播放', click:()=>{win.webContents.send('setplayState',1);updateTrayMenu(1)} },
      { label: '单曲循环', click:()=>{win.webContents.send('setplayState',2);updateTrayMenu(2)} },//改变播放方式 发起通信改变前端组件参数
    ] },
    {type: "separator"},
    { label: '退出', role: 'quit' }
  ];
    function createTray() {
    const tray = new Tray(trayIcon);
    tray.setToolTip('私人订制');
    tray.on('click', () => {
      win.show();
      // 在这里添加你想要的点击事件逻辑
    });
    tray.setContextMenu(Menu.buildFromTemplate(contextMenu));
    app.on('before-quit', () => {
        tray.destroy();
    });
    return tray;
  }
  const tray = createTray()
    /**
   * 设置托盘菜单
   * 这里是改变播放方式 在托盘菜单选型前面加个点
   */
  ipcMain.on('setplayState', (event,args) => {
    updateTrayMenu(args);
  });
  function updateTrayMenu(index){
    for (let i = 0; i < contextMenu[4].submenu.length; i++) {
      if(i == index){
        contextMenu[4].submenu[i].label = `${String.fromCharCode(8226)} `+ contextMenu[4].submenu[i].label
      }else{
        let pattern = `${String.fromCharCode(8226)}`;
        const regexVariable = new RegExp(pattern);
        contextMenu[4].submenu[i].label =  contextMenu[4].submenu[i].label.replace(regexVariable,'');
      }
    }
    tray.setContextMenu(Menu.buildFromTemplate(contextMenu));
  }

preload.js

const { contextBridge, ipcRenderer } = require('electron')
contextBridge.exposeInMainWorld('ipcRenderer', {
  send: (channel, data) => {
    let validChannels = ['toggle-full-screen','minimum','closeProgram','miusic-name','setplayState'] // 配置合法消息名
    if (validChannels.includes(channel)) {
      ipcRenderer.send(channel, data)
    }
  },
  receive: (channel, func) => {
    let validChannels = ['next','pauseOrPlay','setplayState']// 配置合法监听事件名称
    if (validChannels.includes(channel)) {
      ipcRenderer.on(channel, (event, ...args) => func(...args))
    }
  }
})

bottom.vue 播放组件

//收到播放方式改变 设置pinia全局状态的数据 这里TS使用window可能会报错windwo没有ipcRenderer 在上面加上
declare const window :{
  ipcRenderer:{
    receive:Function,
    send:Function,
  }
} & Window

window.ipcRenderer.receive('setplayState',(idx:number)=>{
  store.setStates(idx)
});

接下来继续做桌面歌词 打包双页面

首先需要安装一些依赖: ```bash npm install electron electron-context-menu vite vue@next vue-router@next @vue/compiler-sfc typescript tslib --save-dev ``` 然后在 `src` 目录下新建 `main.ts` 和 `renderer.ts` 两个文件。 `main.ts` 的内容如下: ```ts import { app, BrowserWindow, Menu } from 'electron'; import path from 'path'; import contextMenu from 'electron-context-menu'; // 创建窗口 function createWindow() { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { // 允许使用 node.js nodeIntegration: true, // 允许使用 Electron 的 remote 模块 enableRemoteModule: true, // 允许在渲染进程中使用上下文菜单 contextIsolation: false, }, }); // 加载页面 win.loadFile(path.join(__dirname, '../renderer/index.html')); // 打开开发者工具 win.webContents.openDevTools(); // 设置窗口菜单 const template = [ { label: '菜单1', submenu: [ { label: '子菜单1', click: () => { console.log('点击了子菜单1'); }, }, { label: '子菜单2', click: () => { console.log('点击了子菜单2'); }, }, ], }, { label: '菜单2', click: () => { console.log('点击了菜单2'); }, }, ]; const menu = Menu.buildFromTemplate(template); Menu.setApplicationMenu(menu); } // 当 Electron 初始化完成并准备好创建窗口时调用这个函数 app.whenReady().then(() => { // 注册上下文菜单 contextMenu({ window: BrowserWindow.getFocusedWindow(), showInspectElement: true, }); createWindow(); // 如果所有窗口都关闭了,退出应用 app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); } }); }); // 在 macOS 上,当单击 Dock 图标并且没有其他窗口打开时,重新创建一个窗口 app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } }); ``` `renderer.ts` 的内容如下: ```ts import { createApp } from 'vue'; import App from './App.vue'; createApp(App).mount('#app'); ``` 接下来在 `src` 目录下新建 `index.html` 文件,并且在里面添加一个 `div` 元素,并且指定它的 `id` 为 `app`。同时在 `body` 元素下添加如下代码: ```html <script src="./renderer.js"></script> ``` 最后在 `package.json` 中添加如下脚本: ```json { "scripts": { "start": "vite", "build": "vite build", "electron": "electron ." } } ``` 现在可以运行 `npm run start` 来启动应用程序,然后运行 `npm run electron` 来启动 Electron 应用程序。现在你应该已经能够看到一个 Electron 窗口,并且它包含一个菜单。如果你右键单击窗口,你应该能够看到一个上下文菜单
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值