jnativehook icon indicating copy to clipboard operation
jnativehook copied to clipboard

nativeEvent.getKeyCode() always returns 0 for media keys on linux

Open Bleuzen opened this issue 6 years ago • 4 comments

Hi, in a NativeKeyEvent, getKeyCode() returns always 0 on Manjaro Linux, when I press one of the media keys. On Windows they have a key code.

Here is my code:

import java.util.logging.Level;
import java.util.logging.Logger;

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

public class JNativeHookTestMain implements NativeKeyListener {
	
	public static void main(String[] args) {
		System.out.println("Hi");
		
		Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
		logger.setLevel(Level.WARNING);
		logger.setUseParentHandlers(false);

		try {
			GlobalScreen.registerNativeHook();
			GlobalScreen.addNativeKeyListener(new JNativeHookTestMain());
		} catch (NativeHookException e) {
			e.printStackTrace();
			System.exit(1);
		}
		
		System.out.println("Ready");
	}

	@Override
	public void nativeKeyPressed(NativeKeyEvent nativeEvent) {
		if(nativeEvent.getKeyCode() == NativeKeyEvent.VC_ESCAPE) {
			System.out.println("Bye");
			System.exit(0);
		}
		
		// Prints 0 on linux
		System.out.println(nativeEvent.getKeyCode());
		
		if(nativeEvent.getKeyCode() == NativeKeyEvent.VC_MEDIA_PLAY) {
			// works in Windows, not in Linux
		}
	}

	@Override
	public void nativeKeyReleased(NativeKeyEvent nativeEvent) {}

	@Override
	public void nativeKeyTyped(NativeKeyEvent nativeEvent) {}

}

Bleuzen avatar Jul 01 '17 17:07 Bleuzen

If it is returning Zero it is because the media key is "Unknown." The issue is that the media keys are keyboard dependent and do not have standard codes. Let me know what the KeyEvent.rawCode is for your computer.

kwhat avatar Jul 06 '17 01:07 kwhat

Raw codes: Play key: 65300 Stop key: 65301 Prev key: 65302 Next key: 65303

Edit: I tryed it with a different keyboard and the raw codes are still the same for the media keys. It seems to not depend on the keyboard.

Bleuzen avatar Jul 06 '17 05:07 Bleuzen

I am running on ubuntu 18.04 and can confirm that those raw key codes match also mine (on native laptop keyboard and on external Razr keyboard)

eitzenbe avatar Sep 13 '18 10:09 eitzenbe

I can confirm this is still a problem. Linux is getting a key code lookup overhaul in 2.3 so that should address this problem.

kwhat avatar Mar 11 '22 07:03 kwhat