如何让我的 Java 应用程序在 Windows 中很好地关闭?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/61692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get my Java application to shutdown nicely in windows?
提问by Free Wildebeest
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.
我有一个 Java 应用程序,当用户选择“开始”->“关闭”时,我想“很好地”关闭它。我已经尝试通过 Runtime.addShutdownHook(...) 使用 JVM 关闭侦听器,但这不起作用,因为我不能使用它的任何 UI 元素。
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?
我还尝试在我的主应用程序 UI 窗口上使用退出处理程序,但据我所知,它无法暂停或停止关闭。我怎样才能很好地处理关机?
采纳答案by Steve g
The previously mentioned JNI approach will likely work.
前面提到的 JNI 方法可能会奏效。
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/
您可以使用 JNA,它基本上是 JNI 的包装器,以使其更易于使用。一个额外的好处是它(至少在我看来)通常比原始 JNI 更快且更易于维护。你可以在https://jna.dev.java.net/找到 JNA
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
如果您只是在开始菜单中启动应用程序,因为您试图使其表现得像 Windows 中的服务,则可以使用位于此处的 java 服务包装器:http: //wrapper.tanukisoftware.org/doc /english/download.jsp
回答by Free Wildebeest
As far as I know you need to start using JNI to set up a message handler for the Windows WM_QUERYENDSESSIONmessage.
据我所知,您需要开始使用 JNI 为 Windows WM_QUERYENDSESSION消息设置消息处理程序。
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.
要做到这一点(如果你是新的Windows编程像我一样),你需要创建一个新的类窗口的一个新的消息处理函数(如描述在这里),并处理来自消息处理程序WM_QUERYENDSESSION。
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.
注意:您需要在消息处理线程上使用 JNIEnv::GetJavaVM(...) 和 JavaVM::AttachCurrentThread(...),然后才能从本地消息处理代码调用任何 Java 方法。