How do I get my Java application to shutdown nicely in windows?

你离开我真会死。 提交于 2019-12-18 08:23:48

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/61692/how-do-i-get-my-java-application-to-shutdown-nicely-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!