In OS X (lion) how can I find whether a key combination is in use as a keyboard shortcut?

ぃ、小莉子 提交于 2019-12-06 11:33:50

You can use Carbon to do this. Don't be afraid to use Carbon here, there is no Cocoa way to get this information and the Carbon methods are still supported.

The CopySymbolicHotKeys() function returns an array of dictionaries, containing information about the system-wide symbolic hot keys defined in the Keyboard preferences pane. Each dictionary contains information about a single hot key.

Specifically, each dictionary has three keys:

  • kHISymbolicHotKeyCode: The virtual key code of the hot key, represented as a CFNumber.
  • kHISymbolicHotKeyModifiers: The hot key’s keyboard modifiers, represented as a CFNumber.
  • kHISymbolicHotKeyEnabled: The enabled state of the hot key, represented as a CFBoolean.

Obviously these are raw key codes so you will need to do some work if you want to see what the key codes actually refer to.

Note that the array doesn't contain custom, application-specific hotkeys, but this is a minor problem.

Here's a simple example:

#import <Carbon/Carbon.h>
CFArrayRef registeredHotKeys;


if(CopySymbolicHotKeys(&registeredHotKeys) == noErr)
{
    CFIndex count = CFArrayGetCount(registeredHotKeys);
    for(CFIndex i = 0; i < count; i++)
    {
        CFDictionaryRef hotKeyInfo = CFArrayGetValueAtIndex(registeredHotKeys, i);

        CFNumberRef hotKeyCode = CFDictionaryGetValue(hotKeyInfo, kHISymbolicHotKeyCode);
        CFNumberRef hotKeyModifiers = CFDictionaryGetValue(hotKeyInfo, kHISymbolicHotKeyModifiers);
        CFBooleanRef hotKeyEnabled = CFDictionaryGetValue(hotKeyInfo, kHISymbolicHotKeyEnabled);

        NSLog(@"key code: %@ modifiers: %@ enabled: %@", hotKeyCode, hotKeyModifiers, hotKeyEnabled);

    }

    //you MUST release the dictionary when finished with it
    CFRelease(registeredHotKeys);
}

Remember that you'll need to add the Carbon framework to the Link Binary with Libraries build phase in your project settings.

For more information you should look at the Carbon Event Manager docs (11Mb PDF).

Thear used to be an API in Carbon to get the global keyboard shortcuts, however, I do not believe there is a Cocoa API for this. I don't think you should worry about other third party apps, but you could refer to http://support.apple.com/kb/HT1343 and just hard code to avoid those. He that helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!