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
How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015