如何模拟连续按键

时间:2016-01-24 11:22:10

标签: swift macos cocoa events core-graphics

我需要模拟连续按键。例如,按住' c'键5秒钟。为了模拟按键事件,我尝试使用CGEventCreateKeyboardEvent:

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

但它的作用就像是按下按钮然后立即释放。我需要创建一个持续按住按钮(按下键)然后释放它(按键)的事件。

1 个答案:

答案 0 :(得分: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时点击键盘,则此代码会大写字母。我还注意到,如果光标位置在shift和z被点击之间被改变,则会插入“z”而不是“Z”