electron中showMessageBox里关于选择按钮回调函数不执行的错误

 

一般程序在用户点击窗口右上角关闭按钮时会弹出一个对话框,用来询问用户是否退出程序,用户点击取消或者关闭对话框不会关闭程序,点击确定则会退出程序。在写electron应用时也希望添加这个功能,代码如下:

// 窗口关闭
win.on('close', (e) => {
        // 先阻止默认功能的调用,否则会关闭窗口
        e.preventDefault();
        dialog.showMessageBox(win, {
            type: 'warning',
            title: '关闭',
            message: '是否退出?',
            buttons: ['取消', '确定']
        }, (index) => {
            if (index === 1) {
                win = null;
                app.exit();
            }
        });
});

但是在运行时发现在询问对话框中无论选择什么都不会执行回调函数。

查看electron文档(https://www.electronjs.org/docs/api/dialog)发现在最新版本中的showMessageBox接口已经改了:

 

dialog.showMessageBox([browserWindow, ]options)

参数列表中已经没有回调函数这项了。

返回值:

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

* `response` Number - The index of the clicked button.
* `checkboxChecked` Boolean - The checked state of the checkbox if
`checkboxLabel` was set. Otherwise `false`.

返回值为Promise,所以更改代码为:

// 窗口关闭
win.on('close', (e) => {
        e.preventDefault();
        dialog.showMessageBox(win, {
            type: 'warning',
            title: '关闭',
            message: '是否退出?',
            buttons: ['取消', '确定']
        }).then((index) => {
            if (index.response === 1) {
                win = null;
                app.exit();
            }
        });
});

测试功能正常。 

 

  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值