按住物理键然后使用 awt.Robot 自动按下 Java 中的同一个键

Holding a physical key then using awt.Robot to auto press that same key in Java

我在我的程序中使用 JNativeHook 来检测程序之外的全局击键。 这是我需要完成的:

当我尝试物理按下并按住 space 栏时,在我物理释放 space 栏之前:我想使用 awt.Robot class 在 space 栏被物理按下时自动为我循环按下 space 栏。

我对这个问题的理论是,JNativeHook NativeKeyListener 理解 awt.Robot keyRelease() 函数,就好像它是一个 物理 键释放(在这种情况下 space吧。)

相关代码如下:

// These are the global variables
// ...
Robot robot;  // Initialized in the constructor
// ...
boolean spaceDown = false;
boolean activeThread = false;

private void pressSpace(){

    robot.keyPress(KeyEvent.VK_SPACE);
    robot.delay(20);
    robot.keyRelease(KeyEvent.VK_SPACE);
    robot.delay(30);

    System.out.println("Robot - Press/Release");

}

private void executeThread(){

    new Thread(){
        public void run(){
            while(spaceDown){
                pressSpace();
            }
            activeThread = false;
        }
    }.start();

}

public void nativeKeyPressed(NativeKeyEvent e){

    if(e.getKeyCode() == NativeKeyEvent.VC_SPACE){

        System.out.println("Physical - Pressed");

        activeThread = true;
        spaceDown = true;
        if(activeThread){
            executeThread();
        }
    }

}
public void nativeKeyReleased(NativeKeyEvent e){

    if(e.getKeyCode() == NativeKeyEvent.VC_SPACE){
        System.out.println("Physical - Released");
        spaceDown = false;
    }

}

在 运行 这个程序之后,当我按下 space 键然后释放 或者 如果我按住它。我每次在控制台中得到相同的输出。一般是这样的...

...
Physical - Pressed
Physical - Released
Robot - Press/Release
Physical - Pressed
Physical - Released
Robot - Press/Release
...

有什么想法吗?

我不确定你为什么要这样做...当你按住一个键时,在重复延迟过去后,你基本上会以重复速率按下一个键,直到你释放。如果你想模拟按键弹跳,即按键被按下然后释放,而不是重复按键按下事件:

// These are the global variables
public void nativeKeyPressed(NativeKeyEvent e){

    if(e.getKeyCode() == NativeKeyEvent.VC_SPACE){

        System.out.println("Physical - Pressed");

        // This should produce a key release event.
        GlobalScreen.postNativeEvent(new NativeKeyEvent(
            NativeKeyEvent.NATIVE_KEY_RELEASED, 
            e.getWhen(), 
            e.getModifiers(), 
            e.getRawCode(), 
            e.getKeyCode, 
            e.getKeyChar(), 
            e.getKeyLocation()));
    }

}

你上面的例子有很多线程安全问题,这可能就是你遇到问题的原因。