2016-01-24 96 views
1

我需要模擬連續按鍵。例如按住'c'鍵5秒鐘。爲了模擬按鍵事件我試圖用CGEventCreateKeyboardEvent:如何模擬連續按鍵

let event:CGEventRef! = CGEventCreateKeyboardEvent(nil, 8, true) 
CGEventPost(CGEventTapLocation.CGSessionEventTap, event) 

但是它就像如果按鈕被竊聽,然後立即釋放。我需要創建一個持續按住按鍵(按鍵)然後釋放它(按鍵)的事件。

+0

我不確定我是否理解您要在此處執行的操作。你的意思是按鈕的反應應該延遲5秒,並且只有在5秒內再次按下按鈕纔會觸發按鈕。視覺也需要以某種方式反映這一點?或者,如果用戶在未來5秒內再次按下按鈕,則可能需要在5秒鐘後返回並按住過去的X秒。 (當你需要他的時候Doc Brown在哪裏?) –

+0

我的意思是當用戶按下特定的鍵時,系統應該模擬連續按下。例如,我按下'A'並立即將其釋放,但系統的動作就好像我持有'A'鍵,直到我再次按下它爲止。 –

回答

3

我不確定你試圖達到什麼目的,但看起來系統會繼續按住按鈕。這個簡單的實驗顯示它。

func applicationDidFinishLaunching(aNotification: NSNotification) { 
    print("waiting 4 seconds, use this time to position your cursor in a text field") 
    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(4 * Double(NSEC_PER_SEC))) 
    dispatch_after(delayTime, dispatch_get_main_queue(), { 
     self.insertLetterZ() 
    }) 
} 

func insertLetterZ() { 
    print("pressing shift") 
    self.tapButton(56) 

    print("holding button for 2 seconds") 
    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))) 
    dispatch_after(delayTime, dispatch_get_main_queue(), { 
     print("tapping z, but Z will be selected (since shift is still being pressed)") 
     self.tapButton(6) 

     print("untapping z and shift") 
     self.untapButton(6) 
     self.untapButton(56) 
    }) 
} 

func tapButton(button: CGKeyCode) { 
    let event = CGEventCreateKeyboardEvent(nil, button, true) 
    CGEventPost(CGEventTapLocation.CGSessionEventTap, event) 
} 

func untapButton(button: CGKeyCode) { 
    let event = CGEventCreateKeyboardEvent(nil, button, false) 
    CGEventPost(CGEventTapLocation.CGSessionEventTap, event) 
} 

此代碼然而確實大寫字母,當用戶敲擊鍵盤時移編程按下。我也注意到,如果光標位置在shift和z之間變化,將會插入「z」而不是「Z」