جاوا - آیا راهی در الکترون برای تشخیص خاموش شدن در ویندوز وجود دارد؟
من سعی کردم «session-end» و «window-all-closed» را برای گرفتن رویداد خاموش شدن ویندوز استفاده کنم. Electron نیاز دارد قبل از خاموش شدن کامپیوتر، تابع را فراخوانی کند.
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();
}
});
پاسخ شماره ۱
من یک کتابخانه ساختهام که میتوان از آن برای مسدود کردن و شناسایی خاموش شدن یک برنامه الکترون استفاده کرد: 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();
});
});
});
