• 周五. 9月 30th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Electron 实现最小化到托盘

admin

11月 28, 2021

原生实现 Electron 实现最小化到托盘。

package.json

{
    "name": "electron-tray",
    "version": "1.0.0",
    "description": "",
    "main": "electron.js",
    "scripts": {
        "test": "echo "Error: no test specified" && exit 1",
        "start": "electron ."
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "electron": "^13.1.6"
    }
}

electron.js

/*
 * @Author: Yogile
 * @Gitee: https://gitee.com/yogile
 * @Date: 2021-07-15 19:13:44
 * @LastEditors: Yogile
 * @LastEditTime: 2021-07-16 13:12:58
 * @Description: 
 */
const electron = require('electron');
const { app, Menu, Tray } = electron;
const { BrowserWindow } = electron;
const path = require('path');

let win;
let tray = null

function createWindow() {
    // 创建窗口并加载页面
    win = new BrowserWindow({  800, height: 600, icon: path.join(__dirname, 'yogile-site.ico') });
    win.loadURL(`file://${__dirname}/index.html`);

    // 打开窗口的调试工具
    win.webContents.openDevTools();

    // 关闭默认菜单
    win.setMenu(null);

    // 窗口关闭的监听  
    win.on('closed', (event) => {
        win = null;
    });
    // 触发关闭时触发
    win.on('close', (event) => {
        // 截获 close 默认行为
        event.preventDefault();
        // 点击关闭时触发close事件,我们按照之前的思路在关闭时,隐藏窗口,隐藏任务栏窗口
        win.hide();
        win.setSkipTaskbar(true);

    });
    // 触发显示时触发
    win.on('show', () => {});
    // 触发隐藏时触发
    win.on('hide', () => {});

    // 新建托盘
    tray = new Tray(path.join(__dirname, 'icon.ico'));
    // 托盘名称
    tray.setToolTip('Electron Tray');
    // 托盘菜单
    const contextMenu = Menu.buildFromTemplate([{
            label: '显示',
            click: () => { win.show() }
        },
        {
            label: '退出',
            click: () => { win.destroy() }
        }
    ]);
    // 载入托盘菜单
    tray.setContextMenu(contextMenu);
    // 双击触发
    tray.on('double-click', () => {
        // 双击通知区图标实现应用的显示或隐藏
        win.isVisible() ? win.hide() : win.show()
        win.isVisible() ? win.setSkipTaskbar(false) : win.setSkipTaskbar(true);
    });
}

app.on('ready', createWindow);
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

// 当窗口开始活动时触发
app.on('activate', () => {
    if (win === null) {
        createWindow();
    }
});

发表回复

您的电子邮箱地址不会被公开。