【问题标题】:Holding a physical key then using awt.Robot to auto press that same key in Java按住物理键,然后使用 awt.Robot 在 Java 中自动按下相同的键
【发布时间】:2016-05-17 20:59:20
【问题描述】:

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

当我尝试物理按下并按住空格键时,并且在我物理释放空格键之前:我想使用 awt.Robot 类自动为我按下空格键在物理按下空格键时循环。

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

以下是相关代码:

// 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;
    }

}

运行这个程序后,当我按下空格键,然后如果我按住它就松开OR。每次在控制台中我都会得到相同的输出。一般是这样的……

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

有什么想法吗?

【问题讨论】:

  • 输出继续循环 BTW。

标签: java javafx keylistener awtrobot


【解决方案1】:

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

// 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()));
    }

}

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

【讨论】:

  • 我知道这是主题,但是“线程安全”是指我的布尔变量和我的方法不同步?我想听听你的意见。
  • 您需要同步您的布尔值,并且您可能希望在机器人线程触发之前阻止本机挂钩回调。请参阅等待/通知。
  • 感谢您的意见,会的。另外,一个问题,你的方法似乎有效,直到我按下另一个键和空格键。如果我按空格键然后决定按“h”键,“弹跳”效果似乎停止了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
相关资源
最近更新 更多