How to capture global key presses in java

前端 未结 2 2079
再見小時候
再見小時候 2020-11-28 16:06

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 pla

相关标签:
2条回答
  • 2020-11-28 16:31

    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>
    
    0 讨论(0)
  • 2020-11-28 16:36

    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.

    0 讨论(0)
提交回复
热议问题