macOS App: handling key combinations bound to global keyboard shortcuts

前端 未结 3 611
长发绾君心
长发绾君心 2021-02-04 15:02

In some apps, it makes sense for the app to directly handle keyboard shortcuts which are otherwise bound to system wide combinations. For example, ⌘-Space (normally Spotlight) o

3条回答
  •  耶瑟儿~
    2021-02-04 15:30

    For others looking for a solution for a full-screen app, or if you're willing to take over the full screen, you can use: CGDisplayCapture

    It will cause your app to capture all keyboard input and prevent even Spotlight and App switching from being invoked using a keyboard.

    import Quartz
    
    // disable keyboard events for all apps, except yours
    CGDisplayCapture(CGMainDisplayID())
    
    // reenable keyboard events for other apps
    CGDisplayRelease(CGMainDisplayID())
    

    Note: Until the display is released, the app will not receive window/application active/resign events. So, perhaps you can use mouse tracking to release the display while your app is active. Also, even the screensaver/lock screen will be impacted. Make sure to deactivate the capture as needed.

    Refs:

    • https://lists.apple.com/archives/cocoa-dev/2012/Sep/msg00476.html
    • Monitor screensaver events
    • Display Capture

提交回复
热议问题