views:

2171

answers:

3

I have a Java application which I want to shutdown 'nicely' when the user selects Start->Shutdown. I've tried using JVM shutdown listeners via Runtime.addShutdownHook(...) but this doesn't work as I can't use any UI elements from it.

I've also tried using the exit handler on my main application UI window but it has no way to pause or halt shutdown as far as I can tell. How can I handle shutdown nicely?

+1  A: 

As far as I know you need to start using JNI to set up a message handler for the Windows WM_QUERYENDSESSION message.

To do this (if you're new to Windows programming like me) you'll need to create a new class of window with a new message handling function (as described here) and handle the WM_QUERYENDSESSION from the message handler.

NB: You'll need to use the JNIEnv::GetJavaVM(...) and then JavaVM::AttachCurrentThread(...) on the message handling thread before you can call any Java methods from your native message handling code.

Free Wildebeest
A: 

check the following resources on signal handling with java :

http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/gbzdn.html

http://twit88.com/blog/2008/02/06/java-signal-handling/

Jean
+1  A: 

The previously mentioned JNI approach will likely work.

You can use JNA which is basically a wrapper around JNI to make it easier to use. An added bonus is that it (in my opinion at least) generally is faster and more maintainable than raw JNI. You can find JNA at https://jna.dev.java.net/

If you're just starting the application in the start menu because you're trying to make it behave like a service in windows, you can use the java service wrapper which is found here: http://wrapper.tanukisoftware.org/doc/english/download.jsp

Steve g