我在程序中使用JNativeHook來檢測我的程序之外的全局按鍵筆劃。 這是我需要完成:持有物理密鑰,然後使用awt.Robot自動按下Java中的同一個密鑰
當我嘗試物理按下並按住的空格鍵,和之前我身體釋放的空間吧:我想用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
...
任何想法?
輸出繼續永不結束的循環順便說一句。 –