2016-05-17 14 views
0

我在程序中使用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 
... 

任何想法?

+0

輸出繼續永不結束的循環順便說一句。 –

回答

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

} 

你上面的例子已經很多線程安全問題,這可能是爲什麼你有一個問題。

+0

我知道這是主題的方式,但通過「線程安全」你是指我的布爾變量和我的方法不同步?我希望你對此有所反饋。 –

+0

您需要同步您的布爾值,並且您可能想要阻止本地鉤子回調,直到機器人線程觸發爲止。請參閱等待/通知。 –

+0

感謝您的意見,會做。另外,一個問題,你的方法似乎正在工作,直到我按下另一個鍵和空格鍵。如果我按空格鍵,然後決定按「h」鍵,則「反彈」效果似乎停止。 –

相關問題