codecentric / NSMenuFX

Other
128 stars 27 forks source link

Unable to cancel application closing using Cmd+q #25

Closed liamsharp closed 6 years ago

liamsharp commented 6 years ago

I've created a demo program to highlight this issue, which can be found here: https://github.com/liamsharp/NSMenuFX-quit-issue

The demo program just throws up a pop up allowing you to cancel a setOnCloseRequest by consuming the WindowEvent if the user clicks Cancel.

Using version 2.1.0 when I hit Cmd+q and get the pop up and choose cancel the application stays open as expected. If I rev to 2.1.1 or later in the pom.xml and do the same, the application exits, which it shouldn't.

I think this was introduced here: https://github.com/codecentric/NSMenuFX/commit/e31ac5a15fe8efbf4821046a8eb80d3faf3a641b

Please do let me know if you need anymore info!

0x4a616e commented 6 years ago

Hi, thanks for the report. True, hitting Cmd+Q quits the entire application, but that was intended like that. AFAIK, this is the default behaviour of macOS applications (at least I cannot think of any application where CMD+Q does not exit the application). To just close the focused window, usually CMD+W is used.

0x4a616e commented 6 years ago

Ah, wait, my bad. So what you want to achieve is some dialog asking the user if he really wants to quit the application when CMD+Q is pressed. So first thing is that you can bring back the behaviour of 2.1.0 by calling MenuToolkit.setForceQuitOnCmdQ(false);. In general, you could also try just to "wrap" the onAction property of the quit menu item. One option could be something like this:

        MenuItem quitMenuItem = tk.createQuitMenuItem(appName);
    EventHandler<ActionEvent> defaultAction = quitMenuItem.getOnAction();
    quitMenuItem.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            // Whatever needs to be done...
            defaultAction.handle(event);
        }
    });
liamsharp commented 6 years ago

Thats right, a ways to allow the user to cancel a CMD+Q.

Thanks for the tip, I've gone back to using 2.1.5 and using MenuToolkit.setForceQuitOnCmdQ(false); does the trick.

I had a go with handling the action myself but it doesn't seem to fire. It's not required for my app, but I thought I'd have a play anyway. I've updated the code in https://github.com/liamsharp/NSMenuFX-quit-issue, see aa6b92c1e33a90b19d20cea1a21346d9ee41bf2c if you are interested.

Thanks for your help, much appreciated!