我希望用户能够按住一个键作为硬件输入,而无需在屏幕上输入任何内容。例如,我希望能够使用全局监听器来检测何时按下并按住“a”键,而无需在屏幕上键入“aaaaaaaaaa”。到目前为止,我已经查看了其他一些线程,例如 this ,但我无法有效地将其转换为 Swift 以与我的全局监视器一起使用。如果有人知道如何在 Swift 中执行此操作,那将非常有帮助。这是我目前所拥有的:
func setUpKeyInterception ( ) {
keyDownPort = CGEvent . tapCreate( tap: . cghidEventTap, place: . headInsertEventTap, options: . defaultTap, eventsOfInterest: CGEventMask((1 << CGEventType.keyDown.rawValue)), callback: keyDownCallback , userInfo: UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()))! //keyDownPort is a CFMachPort
keyDownRunLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, keyDownPort , 0) //keyDownRunLoopSource is a CFRunLoopSource
CFRunLoopAddSource(CFRunLoopGetCurrent(), keyDownRunLoopSource, CFRunLoopMode . commonModes)
}
func keyDownCallback ( proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, ptr: UnsafeMutableRawPointer ) -> Unmanaged<CGEvent>? {
if ( event . getIntegerValueField ( CGEventField . keyboardEventKeycode ) == 0x2A ) || ( event . getIntegerValueField ( CGEventField . keyboardEventKeycode ) == 0x51 ){
event . setIntegerValueField ( CGEventField . keyboardEventKeycode , value: 0x03)
}
return nil
}
最佳答案
首先,是否有必要使用全局监视器?。可以通过覆盖包含文本字段的 NSWindow 子类的 sendEvent 方法来拦截重复按键。
class MyWindow: NSWindow {
override func sendEvent(_ event: NSEvent) {
if event.type == .keyDown && event.isARepeat {
return
}
super.sendEvent(event)
}
}
关于Swift,MacOS - 拦截按键并防止在屏幕上打字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54282881/