Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture global key presses in java

Tags:

java

I made a simple Media player in Java but I want to record global key presses like Ctrl + P to pause/resume the current music being played without the JFrame having focus but it seems that its not possible due to JVM security issues.

I came across JNativeHook but I want to implement my own method only for Windows. Please Suggest how to do it and where to begin ?

like image 795
Snehasish Avatar asked Apr 23 '13 22:04

Snehasish


2 Answers

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>
like image 60
Thunder Avatar answered Oct 06 '22 00:10

Thunder


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.

like image 44
Nikola Yovchev Avatar answered Oct 05 '22 23:10

Nikola Yovchev