隐藏mainWindow时多次调用mainWindow.on('close')

时间:2019-03-31 17:37:44

标签: node.js electron

我做了一个基本的电子托盘,当单击其中一个选项时,它会打开一个窗口。我检查是否用bool打开了BrowserWindow并创建或显示/隐藏了窗口。

const contextMenu = Menu.buildFromTemplate([
      { label: 'Open configuration menu', click:() => {
        console.log("called createwin");
        createwin();
      }

createwin是:

function createwin(){
  if (windowshown == false) {
  mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      nodeIntegration: true
    }
  })
  console.log("Window has been created")
  windowshown = true;
mainWindow.loadFile('configuration.html')
}
else {
  mainWindow.show(); 
  console.log("Window has been shown");
} 
  mainWindow.on('close', (event) => {
        event.preventDefault();
        console.log("Window has been hidden");
        mainWindow.hide();
    })
}

当我隐藏/显示它创建的窗口大约4次时,控制台如下所示:


called createwin
Window has been created
window has been hidden
called createwin
Window has been shown
window has been hidden
window has been hidden
called createwin
Window has been shown
window has been hidden
window has been hidden
window has been hidden
called createwin
window has been hidden
window has been hidden
window has been hidden
window has been hidden

第四次后,它只是停止响应。我什至不能

      mainWindow.removeAllListeners('close');
      mainWindow.close()
      mainWindow = null
      app.quit();

我的问题是我的应用程序第四次隐藏窗口后完全变得无响应。

更新:如果我以npm start(而不是Visual Studio代码的调试器)开头,则在隐藏窗口后,该应用程序将变得完全无响应。

我在这里想念什么?

2 个答案:

答案 0 :(得分:1)

由于您是在'close'事件中调用.close(),因此它将进入递归模式并“永远”循环。我觉得.close()方法仅是一个事件触发器,您必须处理关闭过程,因此,不要在事件内部调用.close(),而仅保留空行。

示例:

  mainWindow.removeAllListeners('close');
  // mainWindow.close() delete this line
  mainWindow = null
  app.quit();

答案 1 :(得分:0)

只要您调用error: call to implicitly-deleted default constructor of 'U' U u; note: default constructor of 'U' is implicitly deleted because field 's' has no default constructor S s; ,就会在close事件中添加新的事件侦听器。然后,在关闭窗口时运行每个事件处理程序,从而导致重复的createwin

在创建新窗口时,您只需添加一次事件处理程序:

window has been hidden