Reputation: 493
In my Electron app on MacOS I can get the app to display the main window if the icon in the dock is clicked using the activate
event:
app.on('activate', () => {
log.info('activate')
win.show()
})
Which event to I need to use to display the main window when the user uses Cmd+tab to activate the app? The activate
event is not being fired. The behaviour I'm looking for is like GitHub Desktop where using Cmd+tab to select the app will open the main window if it's not visible.
Upvotes: 2
Views: 1506
Reputation: 1245
Looking at the GitHub Desktop example, it seems like they customize this behaviour by hijacking their BrowserWindow's close
event.
In app/src/main-process/app-window.ts
:
if (__DARWIN__) {
this.window.on('close', e => {
if (!quitting) {
e.preventDefault()
Menu.sendActionToFirstResponder('hide:')
}
})
}
After preventing the window from closing, Menu.sendActionToFirstResponder('hide:')
will hide the entire application instead of doing anything to the window itself. Now, tabbing into the app (as is tabbing into any app hidden with ⌘+H on macOS) will now reveal it.
Note that you should probably add handlers to ensure that the app closes when you're trying to actually quit, as well. From the same file on the GitHub Desktop repo (not sure what triggers the IPC event, but just doing before-quit
works fine to begin with):
let quitting = false
app.on('before-quit', () => {
quitting = true
})
ipcMain.on('will-quit', (event: Electron.IpcMainEvent) => {
quitting = true
event.returnValue = true
})
See a minimal reproduction Gist openable with Electron Fiddle.
Upvotes: 4