我不确定你试图达到什么目的,但看起来系统会继续按住按钮。这个简单的实验显示它。
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”
我不确定我是否理解您要在此处执行的操作。你的意思是按钮的反应应该延迟5秒,并且只有在5秒内再次按下按钮才会触发按钮。视觉也需要以某种方式反映这一点?或者,如果用户在未来5秒内再次按下按钮,则可能需要在5秒钟后返回并按住过去的X秒。 (当你需要他的时候Doc Brown在哪里?) –
我的意思是当用户按下特定的键时,系统应该模拟连续按下。例如,我按下'A'并立即将其释放,但系统的动作就好像我持有'A'键,直到我再次按下它为止。 –