views:

538

answers:

3

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.

A: 

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.

Paul Keeble
A: 

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.

PhiLho
is this process difficult? i have no experience with win32 programming i'm afraid.
Savvas Dalkitsis
A: 

You can add a global event listener to you application using the addAWTEventListener() method in java.awt.Toolkit.

http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#addAWTEventListener%28java.awt.event.AWTEventListener,%20long%29

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);
Aaron
hm... so what happens if i don't have a gui to gain focs in the first place?
Savvas Dalkitsis
If there is no gui then you cannot have KeyEvents from AWT. The only user input for the keyboard without a GUI comes directly from the System.in stream which receives characters typed in the console.If you need to capture events even when your application does not have focus then I think you will need to use JNI to access operating system level hooks as suggested by PhiLho.
Aaron