kwhat / jnativehook

Global keyboard and mouse listeners for Java.
Other
1.75k stars 348 forks source link

Canceling Keyboard Input #328

Closed lasnikr closed 3 years ago

lasnikr commented 3 years ago

I want to replace the windowsshortcut CTRL + V with my own logic. I did it as you already statet here. But I can´t get it to work. When I press the V key I get the output "[ OK ]" but the key comes through. This is my testing class:

package util;

import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;

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

public class CopyCancelingTest {
    public static void main (String[] args) {
        Logger logger = Logger.getLogger(GlobalScreen.class.getPackage().getName());
        logger.setLevel(Level.WARNING);
        logger.setUseParentHandlers(false);
        try {
            GlobalScreen.registerNativeHook();
        }
        catch (NativeHookException ex) {
            System.err.println(ex.getMessage());
            System.exit(1);
        }
        GlobalScreen.addNativeKeyListener(new KeyListenerTest());
    }
}

class KeyListenerTest implements NativeKeyListener {
    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
        if (e.getKeyCode() == NativeKeyEvent.VC_V) {
            try {
                Field f = NativeInputEvent.class.getDeclaredField("reserved");
                f.setAccessible(true);
                f.setShort(e, (short) 0x01);
                System.out.println("[ OK ]");
            }
            catch (Exception ex) {
                System.out.println("[ !! ]");
                ex.printStackTrace();
            }
        }

    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent e) {
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent e) {
    }
}

Notice that I didn´t look for the shortcut but just if the V key is pressed. That is just to make testing easier. I don´t know if this is necessary but I am on Windows 10 and I am using JNativeHook 2.1.0 (Jan 25, 2015).