0

I want to write a program that plays a sound everytime, a button on the Keyboard is pressed. (Even, if the program isn´t in focus) I am using JNativeHook, but when i want to add a Key Listener, i get an error beacuse the method .getInstance isn´t contained in Global Screen. :( Anyone got an idea?

My Code:

package test1;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

public class jNativeHookExample implements NativeKeyListener {

    public void nativeKeyPressed(NativeKeyEvent e) {
        System.out.println(NativeKeyEvent.getKeyText(e.getKeyCode()));

        if (e.getKeyCode() == NativeKeyEvent.VC_F9) {
            //play sound;
        }
    }

    public void nativeKeyReleased(NativeKeyEvent e) {
        System.out.println("Key Released: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public void nativeKeyTyped(NativeKeyEvent e) {
        System.out.println("Key Typed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
    }

    public static void main(String[] args) {
        try {
            /* Register jNativeHook */
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            /* Its error */
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());
            System.exit(1);
        }

        GlobalScreen.getInstance().addNativeKeyListener(new jNativeHookExample());
    }
}
juanjo
  • 3,737
  • 3
  • 39
  • 44

1 Answers1

0

This code is probably ok for the version 1.1 of jnativehook.

Starting from the version 2.0 the GlobalScreen class has no getInstance() method, and addNativeKeyListener() is now static, so it should be called directly on the GlobalScreen:

GlobalScreen.addNativeKeyListener(new jNativeHookExample());
Nina Lisitsinskaya
  • 1,818
  • 11
  • 18