Intercept Command+Q on Mac App before closing?

I like to send my app to a screen allowing data to be saved or cancelling exiting the app. This works fine except when you do a Command+Q or close from the application menu.

Searching so far hasn’t turned up a solution that works.

Is it possible? If so, how?

If a window is open you should be able to use the CancelClose event to do this.

1 Like

Tried it, didn’t work

I just created a sample project (empty) with App CancelClosing and it breaks when using Command+Q

What did you try? Any sample code that you can share?

From the docs:

CancelClosing is called first. If, for any reason, you want to stop the termination process or interact with the user (use a modal window in such a case) to confirm, you should do it in this event. If you return True, the termination process will be stopped immediately.

If you like to Cancel the App to Quit, insert Return True in the event

Function CancelClose() Handles CancelClose as Boolean
  Return True
End Function

In the for App? I tried that, but I’ll try again. If I can’t get it working, I’ll post code.

I set that up as an Event Handler at the App Level. It works, however it also prevents quitting the app even when using “Quit” in code.

How about you set a property that you can change just before your “Quit” command that if true Return False in CancelClosing?

That’s an idea. I just noticed that it’s not an issue in Windows. The first Alt-F4 goes to the window I want to allow data save or whatever. The second time Alt-F4 is pressed it exits which is fine for me. The issue appears tone dealing with it on the Mac.

Well it would do. I use app.CancelClosing to start some final actions, which include running a thread and setting a flag, app.quitting, to True (app.quitting is false normally). Then I Return True to cancel the quit and allow the final actions to complete.

When they are done, I have the thread make a UserInterfaceUpdate request, which simply calls Quit again. This time when my CancelClosing checks Quitting, it is True so it Returns False without doing anything else. App then quits as expected. Simples.

Great suggestion Tim. Using and setting a flag did the trick. Thanks!

If I’ve understood what you are trying to do correctly, Window.CancelClose is the correct way to do it on all platforms.

This has been working successfully for us for 15 years so either something has been broken in Xojo or you are doing something wrong.

Can you share a sample project?

1 Like

I got it working with Tim’s suggestion. Thanks!