electron 有没有办法在电子检测Windows上关机?

fykwrbwg  于 2022-12-08  发布在  Electron
关注(0)|答案(2)|浏览(526)

我尝试了“会话结束”,“窗口全部关闭”来捕获窗口关闭事件。电子需要在计算机关闭之前调用函数。

win.on("session-end",(event) => {
    event.sender.send("appshutdown");
    win = null;
    console.log('app shutdown - main.js');
  });

app.on("window-all-closed", (event) => {
  
  if (process.platform !== "darwin") {
    event.sender.send("appshutdown");
    app.quit();
  }
});
7cjasjjr

7cjasjjr1#

使用节点的行程序结束事件,在行程序结束时执行程式码,这会在系统关闭或重新启动时发生。

process.on('exit', function() {
    // Shutdown logic
});
qzlgjiam

qzlgjiam2#

我创建了一个库,可用于阻止和检测电子应用程序的关闭:https://www.npmjs.com/package/@paymoapp/electron-shutdown-handler
它可以这样使用:

import { app, BrowserWindow } from 'electron';
import ElectronShutdownHandler from '@paymoapp/electron-shutdown-handler';

app.whenReady().then(() => {
    const win = new BrowserWindow({
        width: 600,
        height: 600
    });

    win.loadFile('index.html');

    // you need to set the handle of the main window
    ElectronShutdownHandler.setWindowHandle(win.getNativeWindowHandle());

    // [optional] call this if you want to delay system shutdown.
    // otherwise as soon as the onShutdown callback finishes, the system
    // will proceed with shutdown and the app can be closed any time
    ElectronShutdownHandler.blockShutdown('Please wait for some data to be saved');

    Electron.ShutdownHandler.on('shutdown', () => {
        // this callback is executed when the system is preparing to shut down (WM_QUERYENDSESSION)
        // you can do anything here, BUT it should finish in less then 5 seconds
        // if you call async stuff here, please take into account
        // that if you don't block the shutdown (before the callback is fired)
        // then the system will proceed with shutdown as soon as the function return
        // (no await for async functions)
        console.log('Shutting down!');

        // if you need to call async functions, then do it like this:
        yourAsyncSaveState().then(() => {
            // now we can exit

            // Release the shutdown block we set earlier
            ElectronShutdownHandler.releaseShutdown();
            
            // If you've blocked the shutdown, you should 
            // manually quit the app
            app.quit();
        });
    });
});

相关问题