Swift,MacOS-拦截按键并防止在屏幕上键入

时间:2019-01-21 02:40:51

标签: swift macos

我希望用户能够按住键作为硬件输入,而无需在屏幕上键入任何内容。例如,我希望能够使用全局侦听器来检测何时按住“ a”键,而无需在屏幕上键入“ aaaaaaaaaa”。到目前为止,我已经看过其他一些线程,例如this,但是我无法将其有效地转换为Swift以便与我的Global Monitors一起使用。如果有人知道如何在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

}

1 个答案:

答案 0 :(得分:0)

首先,是否需要使用全局监视器?可以通过覆盖包含文本字段的NSWindow子类的sendEvent方法来拦截重复的按键。

class MyWindow: NSWindow {

    override func sendEvent(_ event: NSEvent) {
        if event.type == .keyDown && event.isARepeat {
            return
        }
        super.sendEvent(event)
    }
}