一般程序在用户点击窗口右上角关闭按钮时会弹出一个对话框,用来询问用户是否退出程序,用户点击取消或者关闭对话框不会关闭程序,点击确定则会退出程序。在写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();
}
});
});
测试功能正常。