我正在使用 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)
})
Run Code Online (Sandbox Code Playgroud)
这会创建按钮,但我在文档中找不到如何从这些按钮获取事件和读取数据的任何地方。如何?
当您Menu.buildFromTemplate实际定义MenuItem对象时。
那些带有签名的单击回调click(menuItem, browserWindow, event)让您几乎可以从包含的 BrowserWindow 访问任何内容
例如
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}
])
Run Code Online (Sandbox Code Playgroud)