【问题标题】:electron: BrowserWindow.on close prompt not working电子:BrowserWindow.on 关闭提示不起作用
【发布时间】:2021-09-20 07:36:17
【问题描述】:

我有一个使用 React 的普通电子应用程序。我想在关闭之前显示一个提示。 预期的行为是当我单击“X”按钮时,窗口必须保持打开状态并在关闭之前显示对话框,以便我可以选择是否真的要退出。 但是,这就是发生的事情 电子窗口在显示对话框之前关闭。在我单击任何按钮之前,对话框会自行关闭。 这是main.dev.ts中包含的代码


 mainWindow.on('close',(e) => {
  var choice = dialog.showMessageBox(mainWindow,
    {
      type: 'question',
      buttons: ['Yes', 'No'],
      title: 'Confirm',
      message: 'Are you sure you want to quit?'
   });
   if(choice == 1){
     e.preventDefault();
   }});

我已经检查过 stackoverflow 上是否有一些帮助问题,但没有找到。 我们将不胜感激。

【问题讨论】:

    标签: electron


    【解决方案1】:

    如果您显示确认提示,您需要致电e.preventDefault(); 以保持窗口打开。

    如果他们点击“是”,则单独关闭窗口。

    但是您会遇到一个问题,即一旦用户单击“是”后窗口关闭,它将再次触发close 事件,从而导致无限循环。我已经用下面的hasConfirmedClose 变量解决了这个问题。

    以下是可行的:

    var hasConfirmedClose = false;
    mainWindow.on('close', (e) => {
        if (!hasConfirmedClose) {
            e.preventDefault(); // Prevent default no matter what.
            var choice = dialog.showMessageBox(mainWindow, {
                type:    'question',
                buttons: ['Yes', 'No'],
                title:   'Confirm',
                message: 'Are you sure you want to quit?'
            });
            if (choice == 1) {
                hasConfirmedClose = true;
                mainWindow.close();
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 2013-09-20
      • 2020-10-06
      • 2015-02-17
      • 2021-02-12
      • 2020-11-04
      • 2018-07-23
      • 1970-01-01
      相关资源
      最近更新 更多