electron 菜单栏
If you are new here, please consider checking out my recent articles on Electron JS including Tray Icons.
如果您是新来的,请考虑查看我最近关于Electron JS的文章, 包括托盘图标 。
In this tutorial, we will set up 2 menu items for a tray icon which when a user right-clicks, the menu appears just like the image below.
在本教程中,我们将为托盘图标设置2个菜单项,当用户右键单击时,菜单如下图所示。
Adding a menu to a system tray icon is the functionality of a tray method known as the tray.setContextMenu(), where the parameter is simply a variable or constant of the menu items passed in Menu.buildFromTemplates([]).
将菜单添加到系统任务栏图标是称为tray.setContextMenu()的任务栏方法的功能,其中参数只是在Menu.buildFromTemplates([])中传递的菜单项的变量或常量。
In this exercise,
在本练习中,
I will create a tray icon first,
我将首先创建一个任务栏图标,
Create a constant which holds the menu items in an array,
创建一个常数,将菜单项保存在一个数组中,
And finally, pass it as a parameter to the tray method setContextMenu().
最后,将其作为参数传递给任务栏方法setContextMenu() 。
We are also going to use the path module which is a Node.Js built-in module to locate the source of our tray icon image and the menu module where the method Menu.buildFromTemplates([]) is derived from.
我们还将使用path模块(它是Node.Js的内置模块)来定位托盘图标图像的源以及菜单模块,该菜单模块是方法Menu.buildFromTemplates([])的来源。
Finally, let us write some code: Open your main JavaScript file and type,
最后,让我们编写一些代码:打开您的主JavaScript文件并键入,
//system tray icon menu//
const electron = require ('electron') // imports electron
const path = require ('path') // imports path module
const {app, Menu, Tray} = electron // imports menu and tray modules
const BrowserWindow = electron.BrowserWindow //enables UI
let mainWindow;
let tray
app.on('ready', _ => {
tray = new Tray (path.join ('src', 'Tray.PNG' ) ) // sets tray icon image
const contextMenu = Menu.buildFromTemplate([ // define menu items
{
label: 'Help',
click: () => console.log ('Help') // click event
},
{
label: 'System',
click: () => console.log ('System')
}
])
tray.setContextMenu(contextMenu)
mainWindow = new BrowserWindow({ // sets browser window dimensions
height : 600,
width : 600,
})
})
Finally, run your code and enjoy the output.
最后,运行您的代码并享受输出。
Output:
输出:
Hey! The browser window displays too... I just did not take a screenshot because it is blank.
嘿! 浏览器窗口也显示...我只是没有截图,因为它是空白的。
Thanks for reading.
谢谢阅读。
Drop your comments if in need of help.
如果需要帮助,请删除您的评论。
翻译自: https://www.includehelp.com/electron-js/add-tray-icon-menu-in-electron-js.aspx
electron 菜单栏