How to intercept CMD+Q from quitting application
We would like to stop users from terminating the application entirely when they hit CMD+Q, by asking them to first confirm through a popup. We are able to register the CMD+Q key event via onKeyEvent as well as onPreviewKeyEvent. However, no matter what we actually do, and despite the fact that we return true to consume the event, exitApplication() seems to always kick in and cancel the application immediately. How can we stop this?
For reference, this is how we're trying to implement it exactly, and we've confirmed that the event is correctly registered. https://github.com/haikalpribadi/typedb-studio/commit/fde7235d46febf50a8864e1a23dd2d8870b55091
@akurasov @igordmn any thoughts on this issue? We need the application to not abruptly quit itself upon CMD+Q critically, and we could use some advice on this, if you have any ideas?
We tried moving the event listener up to the Window onPreviewKeyEvent and it still does not work: https://github.com/haikalpribadi/typedb-studio/commit/08ef5c02aeb3a1f9a81dc4305efc2ad411d18050
The event gets triggered correctly, and we consume the event, but application still immediately terminates.
I am having the exact same issue. I also noticed, that onCloseRequest in Window is triggered when I click on the x button of a window on both macOS and Linux, but it is only triggered on Linux when I close the window using Alt+F4 for example. So the CMD+Q event on macOS is handled in different way. It would be nice to either have onCloseRequest triggered as well on macOS or to have a different callback.
On macOS, the behavior of Cmd+Q and the Quit status bar menu item does seem to be separate from onCloseRequest. It seems that, at least for macOS (I can't speak to other platforms), you need to register a QuitHandler using Desktop.setQuitHandler(QuitHandler). Here's an example:
import java.awt.Desktop
import java.awt.desktop.QuitEvent
import java.awt.desktop.QuitResponse
class Application {
init {
val desktop = Desktop.getDesktop()
if (desktop.isSupported(Desktop.Action.APP_QUIT_HANDLER)) {
desktop.setQuitHandler(::onQuit)
}
}
// ...
fun onQuit(event: QuitEvent, response: QuitResponse) {
// perform whatever actions you want to perform when the user attempts to quit
// then cancel or perform the quit with:
// response.cancelQuit()
// or
// response.performQuit()
}
}
Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.