Electron中实现点击窗口关闭按钮时隐藏而非销毁窗口的问题
Hey there! Let's sort out that close button behavior for your Electron update window. Right now, clicking the title bar's "X" destroys the window entirely—but we can tweak it to just hide the window instead. Here's exactly how to adjust your code:
Modified Code with Explanations
// Make sure you have these imports at the top (if not already there) const { BrowserWindow, url, path } = require('electron'); // Your original window configuration stays mostly the same const updWindow = new BrowserWindow({ width: 400, height: 200, resizable: false, show: false, center: true, maximizable: false, minimizable: false, title: 'Update Available' }); // This is the key fix: intercept the close event updWindow.on('close', function (event) { // Stop Electron from destroying the window by default event.preventDefault(); // Just hide the window so it's still available later updWindow.hide(); }); // Rest of your original setup remains unchanged updWindow.loadURL(url.format({ pathname: path.join(__dirname, 'updateAvailable.html'), protocol: 'file:', slashes: true })); updWindow.setMenuBarVisibility(false);
Why This Works
When you click the title bar's "X", Electron fires the close event. The default behavior is to destroy the window entirely. By adding event.preventDefault(), we block that default action, then call updWindow.hide() to just make the window invisible (it stays in memory, ready to be shown again with updWindow.show() whenever you need it).
Bonus: Handle App Quit Properly
If you want the window to be destroyed normally when the entire app is quitting (not just when the user clicks "X"), add this extra code to avoid leaving the window hanging:
let isAppQuitting = false; // Set a flag when the app is about to quit app.on('before-quit', () => { isAppQuitting = true; }); updWindow.on('close', function (event) { // Only hide the window if the app isn't quitting if (!isAppQuitting) { event.preventDefault(); updWindow.hide(); } });
This way, the window gets cleaned up properly when you shut down the app, but still hides instead of destroying when the user clicks the "X" button.
内容的提问来源于stack exchange,提问作者splash27




