简体   繁体   中英

Is there any way in electron to detect a shutdown on Windows?

I tried "session-end", "window-all-closed" to capture the windows shutdown event. Electron needs to call function before computer gets shutdown.

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();
  }
});

Use node's process exit event to run code when the process is exiting, which happens when a system shutdown or restart occurs.

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

I've made a library that can be used to block and to detect the shutdown of an electron application: https://www.npmjs.com/package/@paymoapp/electron-shutdown-handler

It can be used like this:

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();
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM