Eric Bergman-Terrell's Blog

Java Programming Tip: Enable your SWT/JFace Application to Prompt to Save Changes during Windows Shutdown
January 15, 2009

Applications that edit documents often need to prompt the user to save changes when their documents are "dirty" and Windows is shutting down. It's very easy to do this in an SWT/JFace application written with Eclipse (although it took me quite a while to figure it out).

During shutdown, Windows sends a WM_QUERYENDSESSION message to all applications. If an application returns a zero in response to this message, the shutdown is canceled.

When an SWT/JFace application receives a WM_QUERYENDSESSION message, its Display object fires an SWT.Close event:

...
case OS.WM_QUERYENDSESSION: {
    Event event = new Event ();
    sendEvent (SWT.Close, event);
    if (!event.doit) return 0;
        break;
}
...

All your application needs to do is listen to the Display SWT.Close event, and set event.doit to false if the user chooses to veto the shutdown:

...
// Allow user to save changed when the operating system is being shut down.
Display.getCurrent().addListener(SWT.Close, new Listener() {
    @Override
    public void handleEvent(Event event) {
        boolean cancelled = saveCurrentDocument();

        if (cancelled) {
            event.doit = false;
        }
    }
});
...

NOTE: Make sure your application is NOT running from a console. Otherwise, and I'm guessing here, the console will receive the WM_QUERYENDSESSION, rather than your application. At any rate, if you have the above code responding to the Display SWT.Close event, and the application is not running in a console, your application will be able to prompt to save changes and even stop the shutdown.

You can run your application without a console as follows:

  1. Deploy your application as a .jar file
  2. Run your application with this command: javaw -jar {application jar file path}

Unfortunately this technique does not work on Linux, at least not on Ubuntu. Native Ubuntu applications are able to detect a pending shutdown and prompt the user to save changes, but the Eclipse IDE is not able to.

Keywords: Eclipse, SWT, JFace, Java, Shutdown, WM_QUERYENDSESSION, Display, SWT.Close, Windows

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021
Convert a Windows 10 Notebook into a High-Capacity Photo FrameApril 3, 2021