Tray
概览
This guide will take you through the process of creating a Tray icon with its own context menu to the system's notification area.
在 MacOS 和 Ubuntu, 托盘将位于屏幕右上角上,靠近你的电池和 wifi 图标。 在 Windows 上,托盘通常位于右下角。
示例
main.js
首先,我们需要从 electron
导入 app
, Tray
, Menu
, nativeImage
const { app, Tray, Menu, nativeImage } = require('electron')
下一步我们将创建托盘。 To do this, we will use a NativeImage
icon, which can be created through any one of these methods. Note that we wrap our Tray creation code within an app.whenReady
as we will need to wait for our electron app to finish initializing.
main.js
let tray
app.whenReady().then(() => {
const icon = nativeImage.createFromPath('path/to/asset.png')
tray = new Tray(icon)
// 注意: 你的 contextMenu, Tooltip 和 Title 代码需要写在这里!
})
太好了! 现在我们可以开始将上下文菜单附加到我们的托盘上,就像这样:
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true },
{ label: 'Item4', type: 'radio' }
])
tray.setContextMenu(contextMenu)
上面的代码将在上下文菜单中创建4个单独的 radio-type 单选类型项。 To read more about constructing native menus, click here.
最后,让我们给我们的托盘一个工具提示和标题。
tray.setToolTip('This is my application')
tray.setTitle('This is my title')
结论
在启动应用后,你应该看到屏幕的顶部或底部右侧的托盘, 具体位置取决于操作系统。
fiddle docs/latest/fiddles/native-ui/tray