【发布时间】:2021-09-22 08:28:06
【问题描述】:
如何从电子托盘图标打开一个新窗口
目前我正在尝试创建一个窗口小部件。 我遇到了 3 个问题。
- 在托盘图标右键菜单中创建复选框之前是成功的。 但是我想在单击复选框时显示一个新窗口。 (因为我想做一个设置菜单)
我尝试在托盘图标上打开一个新窗口,但很难理解,因为使用“远程”有很多过时的信息。 (目前不推荐使用远程。https://www.electronjs.org/docs/api/remote)
-
第二个问题,我在托盘图标的右键菜单中设置了“always on top”,但是没有用。
-
想添加关闭应用时记住窗口位置和启动应用时恢复坐标的过程,但出现错误。
const {app, BrowserWindow, Menu, Tray} = require('electron')
const path = require('path')
const url = require('url')
// Multiple execution prevention
const doubleboot = app.requestSingleInstanceLock();
if(!doubleboot){
app.quit();
}
let win
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 800,
height: 600,
transparent:true,
frame:false,
resizable:false,
webPreferences: {
nodeIntegration: true,
},
alwaysOnTop : false,
})
// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
win.webContents.openDevTools()
// Restore window position
if (localStorage.getItem("windowPosition")) {
var pos = JSON.parse(localStorage.getItem("windowPosition"));
win.setPosition(pos[0], pos[1]);
}
// Emitted when the window is closed.
win.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
// win = null
// Save window position when closed
localStorage.setItem("windowPosition", JSON.stringify(win.getPosition()));
})
}
// https://www.electronjs.org/docs/api/tray
app.whenReady().then(() => {
tray = new Tray('./img/icon.ico')
const contextMenu = Menu.buildFromTemplate([
{ label: 'Always on top', type: 'checkbox'},
{ label: "Focus", click: function () { win.focus(); } },
{ label: 'Settings', click: function () { window.open()} },
{ label: "Exit", click: function () { win.close(); } }
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
contextMenu.items[0].checked = false
//always on top
function checked(){
if (contextMenu.items[0] === 0 ){
win.alwaysOnTop = true;
}
else {
win.alwaysOnTop = false;
}
}
})
app.on('ready', createWindow)
// app.on('window-all-closed', () => {
// if (process.platform !== 'darwin') {
// app.quit()
// }
// })
// app.on('activate', () => {
// if (win === null) {
// createWindow()
// }
// })
【问题讨论】:
标签: javascript electron