1. 程式人生 > 其它 >electron 關閉視窗提示框 關閉確認 關閉彈窗 提示窗

electron 關閉視窗提示框 關閉確認 關閉彈窗 提示窗

目的及效果

點選視窗右上角的叉叉的時候,彈出下面這個,點選確認則程式結束,取消則提示框關閉,程式繼續
在這裡插入圖片描述

  • 環境:electron version: 11.0.4
  • main.js程式碼
var electron = require('electron')
app.on('ready', () => {
    mainWindow = new BrowserWindow({
        width: 1500,
        height: 800,
        minHeight: 800,
        minWidth: 1500,
        // fullscreen: true,
        webPreferences:
{ nodeIntegration: true, enableRemoteModule: true, webviewTag: true, }, }) mainWindow.loadFile('index.html') //mainWindow要關閉時的方法↓ mainWindow.on('close', e => { e.preventDefault(); //先阻止一下預設行為,不然直接關了,提示框只會閃一下 electron.dialog.
showMessageBox({ type: 'info', title: '提示', message:'確認退出?', buttons: ['確認', '取消'], //選擇按鈕,點選確認則下面的idx為0,取消為1 cancelId: 1, //這個的值是如果直接把提示框×掉返回的值,這裡設定成和“取消”按鈕一樣的值,下面的idx也會是1 }).then(idx => { //注意上面↑是用的then,網上好多是直接把方法做為showMessageBox的第二個引數,我的測試下不成功
console.log(idx) if (idx.response == 1) { console.log('index==1,取消關閉') e.preventDefault(); } else { console.log('index==0,關閉') mainWindow = null app.exit(); } }) }); })