問題描述
我希望我的 Electron.js 應用程序存在于系統托盤上,并且每當用戶想要做某事時他們可以從系統托盤恢復做一些事情并將其最小化/關閉回到系統托盤.我該怎么做?
I want my Electron.js application to live on system tray and whenever the user wants to do something they can restore from the system tray do something and minimize/close it back to system tray. How do i do that?
我從文檔中看到了 tray
部分,但對實現我想要的沒有多大幫助.
I've seen the tray
section from the documentation but doesn't help much to achieve what i want.
這是我目前在 main.js
文件中得到的內容
Here is what i got so far on the main.js
file
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 存儲庫,但它在 linux 上無法正常工作.
I found this menubar repo, but it won't work as expected on linux.
推薦答案
其實我很久以前就想出來了,但是對于遇到同樣問題的人來說,這是一種可以實現最小化到 tray
并從 tray
恢復.訣竅是捕捉 close
和 minimize
事件.
I actually figured it out a long time ago but for folks who encounter the same problem here is one way you could achieve minimizing to tray
and restoring from tray
. The trick is to catch the close
and minimize
events.
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();
} }
]);
這篇關于Electron.js 如何最小化/關閉系統托盤的窗口并從托盤恢復窗口?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!