Key events on application level in Java
-
18-09-2019 - |
Question
Is it possible to be notified of key events on an application level and not on a Component level? What i mean by application level is not having a swing component receive key events but to have a special class listen to system wide key events.
This could be used in an app with no GUI for instance or when a more global handling of key events is needed.
Solution
Not sure if it is possible in native Java: in Windows, you have to create a DLL to hook key events at the system (global) level, I suppose it is a different mechanism in Unix or MacOS, so you have to interface to low level system API to get this done.
OTHER TIPS
You can add a global event listener to you application using the addAWTEventListener() method in java.awt.Toolkit.
Of course this will only work when your application has focus.
So for key events you could use:
public class MyGlobalKeyListener implements AWTEventListener {
public void eventDispatched(AWTEvent event) {
// do something here
}
}
// Then on startup register.
AWTEventListener myGlobalKeyListener = new MyGlobalKeyListener();
Toolkey.getDefaultToolkit().addAWTEventListener(myGlobalKeyListener, AWTEvent.KEY_EVENT_MASK);
Signals are not a universal concept, but certain signals like ctrl+c for shutdown are widespread if not used everywhere. That particular signal can be listened to using a shutdown hook. Calling Runtime.addShutdownHook(Thread) will allow you to know when the VM is being closed for whatever reason and do something on that event.