javawindowseventsshutdown-hook

Detect windows logout event in Java application


Is there a library that I can use with Java to listen for user logout and possibly other Windows events? (Even better if it supports multiple platforms!)

I remember reading about a library of this sort a number of years ago, but can't seem to find it now. I've seen other threads to do essentially the same thing using Python with win32ts.

Also better if it's free and/or open source.

Thanks.

Note: The candidate solution of using Runtime.getRuntime().addShutdownHook(Thread) does not work correctly with javaw. I am still looking for a solution that will work with javaw. See java bug ids 4486580 and 4302814. Thanks --cam


Solution

  • I think you want to look at Runtime.addShutdownHook(). This gives you the last-ditch opportunity to do things before the JVM shuts down. This lets you detect an actual logout where all of the applications are shutdown, but not they just temporarily switch users, leaving their state ready to come back to. However, as a warning, whatever you plan on doing during the shutdown process needs to be brief since the OS may SIGKILL (or the equivalent) on you at any time, which halts the JVM immediately.

    If this isn't what you need, you're probably going to need to use JNI to register a native listener. As for the other windows events, the AWT library provides a number of classes for implementing the listeners that most normal apps would be interested in. In this case, you might be interested in a FocusEvent.