如何与托盘菜单上的电子单选按钮交互?



我正在使用Electron,我正在为我的应用程序创建一个托盘图标。Electron自己的文档(https://electronjs.org/docs/api/tray#tray-popupcontextmenu-position-os-x-windows(显示,我可以使用以下代码在菜单上选择单选按钮:

const {app, Menu, Tray} = require('electron')
let tray = null
app.on('ready', () => {
tray = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([
{label: 'Item1', type: 'radio'},
{label: 'Item2', type: 'radio'},
{label: 'Item3', type: 'radio', checked: true},
{label: 'Item4', type: 'radio'}
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
})

这将创建按钮,但我在文档中找不到如何获取事件并从这些按钮读取数据。如何?

当你Menu.buildFromTemplate时,你实际上定义了MenuItem对象。

那些具有带有签名的单击回调click(menuItem, browserWindow, event)可让您从包含的浏览器窗口中访问几乎任何内容

例如

const handleClick = (menuItem, browserWindow, event) => {
// ...
}
const contextMenu = Menu.buildFromTemplate([
{label: 'Item1', type: 'radio', click: handleClick},
{label: 'Item2', type: 'radio', click: handleClick},
{label: 'Item3', type: 'radio', click: handleClick, checked: true},
{label: 'Item4', type: 'radio', click: handleClick}
])

最新更新