How to capture global key presses in java

Try JNativeHook. Here is a sample that shows how to use it to capture global key presses:

try
{
    GlobalScreen.registerNativeHook();
    GlobalScreen.addNativeKeyListener(new NativeKeyListener()
    {

        @Override
        public void nativeKeyTyped(NativeKeyEvent nativeEvent)
        {
        }

        @Override
        public void nativeKeyReleased(NativeKeyEvent nativeEvent)
        {
            String keyText=NativeKeyEvent.getKeyText(nativeEvent.getKeyCode());
            System.out.println("User typed: "+keyText);
        }

        @Override
        public void nativeKeyPressed(NativeKeyEvent nativeEvent)
        {   
        }
     });
}
catch (NativeHookException e)
{
    e.printStackTrace();
}

If you are using maven, add this to your pom.xml:

<dependency>
    <groupId>com.1stleg</groupId>
    <artifactId>jnativehook</artifactId>
    <version>2.1.0</version>
</dependency>

Jintellitype is a somewhat easy solution.

https://code.google.com/p/jintellitype/

The other easy solution would be to use a windows hook with JNA:

JNA Keyboard Hook in Windows

I have some experience with JNA and have really liked the api.

And a third solution would be to manage your own calls with JNI.

Portability-wise, as far as I know, windows dlls and api architecture as far as responding to user input, has been preserved in different OS versions. If memory serves, hooks for user input are in the user32 dll. Maybe you have to jump through some hoops for a x64 bit version, but I doubt it would be that hard.

Tags:

Java