How to listen to global hotkeys with Swift in an OS X app?

前端 未结 6 1755
北荒
北荒 2020-12-12 17:08

I\'m trying to have a handler in my Mac OS X app written in Swift for a global (system-wide) hotkey combo but I just cannot find proper documentation for it. I\'ve read that

6条回答
  •  温柔的废话
    2020-12-12 18:03

    I don't believe you can do this in 100% Swift today. You'll need to call InstallEventHandler() or CGEventTapCreate(), and both of those require a CFunctionPointer, which can't be created in Swift. Your best plan is to use established ObjC solutions such as DDHotKey and bridge to Swift.

    You can try using NSEvent.addGlobalMonitorForEventsMatchingMask(handler:), but that only makes copies of events. You can't consume them. That means the hotkey will also be passed along to the currently active app, which can cause problems. Here's an example, but I recommend the ObjC approach; it's almost certainly going to work better.

    let keycode = UInt16(kVK_ANSI_X)
    let keymask: NSEventModifierFlags = .CommandKeyMask | .AlternateKeyMask | .ControlKeyMask
    
    func handler(event: NSEvent!) {
        if event.keyCode == self.keycode &&
            event.modifierFlags & self.keymask == self.keymask {
                println("PRESSED")
        }
    }
    
    // ... to set it up ...
        let options = NSDictionary(object: kCFBooleanTrue, forKey: kAXTrustedCheckOptionPrompt.takeUnretainedValue() as NSString) as CFDictionaryRef
        let trusted = AXIsProcessTrustedWithOptions(options)
        if (trusted) {
            NSEvent.addGlobalMonitorForEventsMatchingMask(.KeyDownMask, handler: self.handler)
        }
    

    This also requires that accessibility services be approved for this app. It also doesn't capture events that are sent to your own application, so you have to either capture them with your responder chain, our use addLocalMointorForEventsMatchingMask(handler:) to add a local handler.

提交回复
热议问题