dialog.showMessageBox 不返回电子 main.js 中的按钮索引

时间:2023-03-06
本文介绍了dialog.showMessageBox 不返回电子 main.js 中的按钮索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个消息框,当用户单击dashboardWindow 上的关闭时会打开一个消息框(Windows 操作系统右上角的X 按钮)

I have a messagebox that will open when the user click close on dashboardWindow (X button top right on windows os)

dashboardWindow.on("close", (event) => {
    event.preventDefault();
    console.log("before message box");
    dialog.showMessageBox(
      dashboardWindows,
      {
        message: "Test",
        buttons: ["Default Button", "Cancel Button"],
        defaultId: 0, // bound to buttons array
        cancelId: 1 // bound to buttons array
      },
      (response) => {
        if (response === 0) {
          // bound to buttons array
          console.log("Default button clicked.");
        } else if (response === 1) {
          // bound to buttons array
          console.log("Cancel button clicked.");
        }
      }
    );
    console.log("after message box");
  });
}

当我关闭 dashboardWindow 时消息框打开,但我无法让 response === 0 工作.即使没有点击按钮,console.log("after message box"); 也已经运行.我怎样才能做出响应(messageBox 上的返回索引按钮)?

The messagebox opened when i close the dashboardWindow but i can't get response === 0 to work. Samehow console.log("after message box"); already run even when there is no click on the buttons. How I can make the response work (return index button on messageBox)?

登录窗口关闭

推荐答案

请参考最新的 API 文档关于 dialog.showMessageBox:此方法返回一个 Promise 对象并且不再使用回调函数,就像在 Electron v5.xx 之前一样

Please refer to the most recent API doc about dialog.showMessageBox: this method returns a Promise object and doesn't make use of a callback function any more, like it used to until Electron v5.x.x.

Returns Promise - 使用包含以下属性:

Returns Promise<Object> - resolves with a promise containing the following properties:

  • response Number - 点击按钮的索引.
  • checkboxChecked 布尔值 - 如果设置了 checkboxLabel,则复选框的选中状态.否则 false.
  • response Number - The index of the clicked button.
  • checkboxChecked Boolean - The checked state of the checkbox if checkboxLabel was set. Otherwise false.

这应该可以工作(尽管在您的上下文中未经测试):

This should work then (untested in your context though):

dashboardWindow.on("close", (event) => {
    event.preventDefault();
    console.log("before message box");
    dialog.showMessageBox(
      dashboardWindows,
      {
        message: "Test",
        buttons: ["Default Button", "Cancel Button"],
        defaultId: 0, // bound to buttons array
        cancelId: 1 // bound to buttons array
      })
      .then(result => {
        if (result.response === 0) {
          // bound to buttons array
          console.log("Default button clicked.");
        } else if (result.response === 1) {
          // bound to buttons array
          console.log("Cancel button clicked.");
        }
      }
    );
    console.log("after message box");
  });

这篇关于dialog.showMessageBox 不返回电子 main.js 中的按钮索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!