Detect windows logout event in Java application

杀马特。学长 韩版系。学妹 提交于 2019-11-29 12:08:17

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.

My best guess would be to use a ShutdownHook. You can register a thread which is invoked as soon as the JVM is beeing shut down.

Edit:
If you want to realize this under windows, you could create an invisible window and react on the WM_QUERYENDSESSION message which is sent by the OS upon user log off or system shutdown.

There seems to be a lot of people that are running into this issue. Although, the people on the Java project obviously don't consider this much of a priority (The original ticket was opened almost 10 years ago).

I have had some success with the work-around posted in bug 4486580 which uses the hidden JWindow. However, this work-around is considered unreliable. I also found this little bit of discussion started by cowwoc who posted the work-around: http://forums.java.net/jive/thread.jspa?threadID=46716. This work-around is better than nothing, but it would be nice to block a windows logout until the program has definitely finished cleanup. You don't want to be part-way through the process when the process is terminated.

The most recent bug opened surrounding this issue is 6798985. It seems to have gone mostly unnoticed.

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