【发布时间】: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