Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  61] [ 4]  / answers: 1 / hits: 28287  / 7 Years ago, thu, march 23, 2017, 12:00:00

Instead of quit the application, I'd like to hide the main window when the system close button is clicked and show the main window when the application is clicked or activate. I'm using the following code to do this on my Electron app:



'use strict'

import { app, BrowserWindow } from 'electron'

let mainWindow
const winURL = process.env.NODE_ENV === 'development'
? `http://localhost:${require('../../../config').port}`
: `file://${__dirname}/index.html`

function createWindow () {
/**
* Initial window options
*/
mainWindow = new BrowserWindow({
height: 620,
width: 350,
resizable: true,
fullscreenable: true
})

mainWindow.loadURL(winURL)

mainWindow.on('closed', () => {
mainWindow.hide()
})

// eslint-disable-next-line no-console
console.log('mainWindow opened')
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
mainWindow.show()
})


But, hiding and showing the window from the activate and closed event shows the following error and never show the main window when the application is active.



Uncaught Exception:
Error: Object has been destroyed
at BrowserWindow.<anonymous> (/app/src/main/index.js:24:16): mainWindow.on('closed')


Not sure what else to do.


More From » electron

 Answers
5

My solution is this:



import { app, BrowserWindow } from 'electron'

let win = null

function createWindow () {
win = new BrowserWindow({width: 1024, height: 768})
win.loadURL('...')
win.webContents.openDevTools()
win.on('close', (event) => {
if (app.quitting) {
win = null
} else {
event.preventDefault()
win.hide()
}
})
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => { win.show() })

app.on('before-quit', () => app.quitting = true)


In this way on OSX if you close the window, the window simply hide, if you close the app with cmd+Q the app terminate.


[#58412] Wednesday, March 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;