系统功能

这篇笔记我们简单介绍Electron框架中和系统相关的功能,由于这些功能和操作系统紧密相关,因此这里仅以Windows为例进行介绍。

托盘图标

Windows的托盘一般位于右下角,下面代码我们为程序添加了一个托盘图标,并为其添加了一个菜单,点击菜单中的Exit选项时将退出程序。

const { app, BrowserWindow, Tray, Menu, nativeImage } = require('electron');
const path = require('path');

const createWindow = () => {
    // 创建窗口
    const window = new BrowserWindow({
        width: 800,
        height: 600
    });

    // 加载HTML文件
    window.loadFile('index.html');
};

app.whenReady().then(() => {
    const trayIcon = nativeImage.createFromPath(path.join(__dirname, 'assets/icon.png'));
    const tray = new Tray(trayIcon);
    const trayMenu = Menu.buildFromTemplate([
        {label: 'Exit', click: () => {app.quit()}}
    ]);
    tray.setContextMenu(trayMenu);
    tray.setTitle('my title');
    tray.setToolTip('my tooltip');

    createWindow();

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow();
        }
    })
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。
Copyright © 2017-2024 Gacfox All Rights Reserved.
Build with NextJS | Sitemap