NodeJS Electron.js如何最小化/关闭窗口到系统托盘,并从托盘恢复窗口?

csga3l58  于 2022-11-04  发布在  Node.js
关注(0)|答案(8)|浏览(1332)

我希望我的Electron.js应用程序生活在系统托盘上,每当用户想做的事情,他们可以从系统托盘恢复做一些事情,并最小化/关闭它回到系统托盘。我该怎么做?
我已经从文档中看到了tray部分,但它对实现我想要的东西没有太大帮助。
下面是我目前在main.js文件中得到的结果。

var application = require('app'),
    BrowserWindow = require('browser-window'),
    Menu = require('menu'), 
    Tray = require('tray'); 
application.on('ready', function () {
    var mainWindow = new BrowserWindow({
        width: 650,
        height: 450,
        'min-width': 500,
        'min-height': 200,
        'accept-first-mouse': true,
        // 'title-bar-style': 'hidden',
        icon:'./icon.png'
    });
    mainWindow.loadUrl('file://' + __dirname + '/src/index.html');
    mainWindow.on('closed', function () {
        mainWindow = null;
    });
    mainWindow.setMenu(null);

    var appIcon = null;
    appIcon = new Tray('./icon-resized.png');
    var contextMenu = Menu.buildFromTemplate([
        { label: 'Restore', type: 'radio' }
    ]);
    appIcon.setToolTip('Electron.js App');
    appIcon.setContextMenu(contextMenu);
});

更新日期:

我找到了这个menubar repo,但它在linux上无法正常工作。

wfauudbj

wfauudbj1#

我其实很久以前就发现了这个问题,但是对于遇到同样问题的人来说,这里有一种方法可以实现最小化到tray并从tray恢复。诀窍是捕获closeminimize事件。

var BrowserWindow = require('browser-window'),

var mainWindow = new BrowserWindow({
    width: 850,
    height: 450,
    title: "TEST",
    icon:'./icon.png'
});

mainWindow.on('minimize',function(event){
    event.preventDefault();
    mainWindow.hide();
});

mainWindow.on('close', function (event) {
    if(!application.isQuiting){
        event.preventDefault();
        mainWindow.hide();
    }

    return false;
});

和从Tray还原

var contextMenu = Menu.buildFromTemplate([
    { label: 'Show App', click:  function(){
        mainWindow.show();
    } },
    { label: 'Quit', click:  function(){
        application.isQuiting = true;
        application.quit();
    } }
]);
2wnc66cl

2wnc66cl2#

除了以上的答案-isQuiting标志也值得在应用程序的before-quit回调中设置。这样,如果操作系统或用户以其他方式请求关闭应用程序,例如通过Macos Dock任务栏的退出命令。完整的Typescript友好代码段:

import {app, BrowserWindow, Tray, Menu} from 'electron';
import * as path from 'path';

let window;
let isQuiting;
let tray;

app.on('before-quit', function () {
  isQuiting = true;
});

app.on('ready', () => {
  tray = new Tray(path.join(__dirname, 'tray.png'));

  tray.setContextMenu(Menu.buildFromTemplate([
    {
      label: 'Show App', click: function () {
        window.show();
      }
    },
    {
      label: 'Quit', click: function () {
        isQuiting = true;
        app.quit();
      }
    }
  ]));

  window = new BrowserWindow({
    width: 850,
    height: 450,
    show: false,
  });

  window.on('close', function (event) {
    if (!isQuiting) {
      event.preventDefault();
      window.hide();
      event.returnValue = false;
    }
  });
});
zrfyljdw

zrfyljdw3#

我更新了一个场景的代码,如果你想显示图标在您的系统托盘上的所有时间,直到你不退出应用程序

var { app, BrowserWindow, Tray, Menu } = require('electron')
var path = require('path')
var url = require('url')
var iconpath = path.join(__dirname, 'user.ico') // path of y
var win
function createWindow() {
    win = new BrowserWindow({ width: 600, height: 600, icon: iconpath })

    win.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
    }))

    var appIcon = new Tray(iconpath)

    var contextMenu = Menu.buildFromTemplate([
        {
            label: 'Show App', click: function () {
                win.show()
            }
        },
        {
            label: 'Quit', click: function () {
                app.isQuiting = true
                app.quit()
            }
        }
    ])

    appIcon.setContextMenu(contextMenu)

    win.on('close', function (event) {
        win = null
    })

    win.on('minimize', function (event) {
        event.preventDefault()
        win.hide()
    })

    win.on('show', function () {
        appIcon.setHighlightMode('always')
    })

}

app.on('ready', createWindow)
isr3a4wc

isr3a4wc4#

对于那些不想改变minimize行为的人来说,一个比使用标志更好的方法是:
通常使用mainWindow.hide()隐藏close事件上的窗口

mainWindow.on('close', function (event) {
    event.preventDefault();
    mainWindow.hide();
});

然后调用mainWIndow.destroy()强制关闭窗口,同时保证执行closed事件处理函数。
从文档中:
强制关闭窗口,网页不会发出unload和beforeunload事件,该窗口也不会发出close事件,但保证会发出closed事件。

var contextMenu = Menu.buildFromTemplate([
    { label: 'Show App', click:  function(){
        mainWindow.show();
    } },
    { label: 'Quit', click:  function(){
        mainWindow.destroy();
        app.quit();
    } }
]);
6l7fqoea

6l7fqoea5#

这是用NW.js标记的,因为所有其他答案都是针对Electron的,所以我想我应该展示一下NW.js中的一切总是多么容易。这里设置了一个简单的演示存储库:

只需下载并运行npm install && npm start

icomxhvb

icomxhvb6#

我分享我的草图,最小化隐藏在任务栏图标,菜单选项右键单击图标恢复/关闭。使用websocket/http服务器。

//const {app, BrowserWindow} = require('electron');
const {app, BrowserWindow, Tray, Menu} = require('electron');
const myip = require('quick-local-ip');
const express = require('express');
const WebSocket = require('ws');
const bodyParser = require('body-parser');
const path = require('path')
// Config
const Config = {
    http_port: '8080',
    socket_port: '3030'
};

var iconpath = path.join(__dirname, 'rfid.png') // path of y

// Http server
const _app = express();
const server = require('http').Server(_app);
server.listen(Config.http_port);

// WSS server
const wss = new WebSocket.Server({port: Config.socket_port});

// Console print
console.log('[SERVER]: WebSocket on: ' + myip.getLocalIP4() + ':' + Config.socket_port); // print websocket ip address
console.log('[SERVER]: HTTP on: ' + myip.getLocalIP4() + ':' + Config.http_port); // print web server ip address

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

let window;
let isQuiting;
let tray;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        acceptFirstMouse: true,
        autoHideMenuBar: false,
        useContentSize: true,
    });

    var appIcon = new Tray(iconpath);

    // mainWindow.loadURL('index.html')
    mainWindow.loadURL('http://localhost:8080');
    mainWindow.focus();
    // mainWindow.setFullScreen(true);

    // Open the DevTools.
    mainWindow.webContents.openDevTools();

    var contextMenu = Menu.buildFromTemplate([
        {
            label: 'Show App', click: function () {
                mainWindow.show()
            }
        },
        {
            label: 'Quit', click: function () {
                app.isQuiting = true
                app.quit()
            }
        }
    ])

    appIcon.setContextMenu(contextMenu)

    // Emitted when the window is closed.
    mainWindow.on('close', function (event) {
        mainWindow = null
    });

    mainWindow.on('minimize', function (event) {
        event.preventDefault()
        mainWindow.hide()
    });

    mainWindow.on('show', function () {
        appIcon.setHighlightMode('always')
    })
}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
})

/**
 * EXPRESS
 */
_app.use(bodyParser.urlencoded({
    extended: false
}));

_app.use('/assets', express.static(__dirname + '/www/assets'))

_app.get('/', function (req, res) {
    res.sendFile(__dirname + '/www/index.html');
});

/**
 * WEBSOCKET
 */
wss.getUniqueID = function () {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    }

    return s4() + s4() + '-' + s4();
};

wss.on('connection', function connection(ws, req) {
    ws.id = wss.getUniqueID();
    console.log('[SERVER]: Client Connected. ID=', ws.id);

    ws.on('close', function close() {
        console.log('[SERVER]: Client disconnected.');
    });

    ws.on('message', function incoming(recieveData) {
        console.log('[SERVER] Message:', recieveData);

        // Example use
        // send(recieveData);

        sendAll(recieveData);
    });

    // Send back to client
    function send(data) {
        data = JSON.stringify(data);
        ws.send(data);
    }

    // Send to all clients
    function sendAll(data) {
        data = JSON.stringify(data);

        wss.clients.forEach(function each(client) {
            client.send(data);
        });
    }
});
dphi5xsq

dphi5xsq7#

我的解决方案:

let ownIsHidden: boolean;

mainWindow.on('show', () => {
    ownIsHidden = false;
  });

mainWindow.on('hide', function () {
    ownIsHidden = true;
  });

tray.on('mouse-down', () => {
    if (ownIsHidden) {
      mainWindow?.show();
    } else {
      mainWindow?.hide();
    }
  });
2w3kk1z5

2w3kk1z58#

尝试最小化事件而不是隐藏。

var BrowserWindow = require('browser-window'),

var mainWindow = new BrowserWindow({
    width: 850,
    height: 450,
    title: "TEST",
    icon:'./icon.png'
});

mainWindow.on('minimize',function(event){
    event.preventDefault();
    mainWindow.minimize();
});

mainWindow.on('close', function (event) {

  event.preventDefault();
  mainWindow.minimize();
    return false;
});

这对我很有效。hide()正在关闭Windows。

相关问题