Detect windows logout event in Java application

大憨熊 提交于 2019-11-28 05:41:15

问题


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


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/512555/detect-windows-logout-event-in-java-application

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