如何模拟连续按键

How to simulate a continuous key press

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

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

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

我不确定你想要达到什么目的,但系统似乎会继续按住按钮。这个简单的实验证明了这一点。

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"