Date
Sep. 8th, 2024
 
2024年 8月 6日

Post: Mac: 注册全局热键

Mac: 注册全局热键

Published 12:04 Apr 20, 2014.

Created by @ezra. Categorized in #Programming, and tagged as #macOS.

Source format: Markdown

Table of Content

使用 Cocoa 为应用注册热键, 首先需要引入 Carbon.framework, 并包含头文件。

#import <Carbon/Carbon.h>

接下来, 要做两件事, 注册热键、设置回调。

回调设置:

OSStatus MXHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData) {
    // ... callback
    return noErr;
}

注册热键:

- (void)registerKey {
    EventHotKeyRef       gMyHotKeyRef;
    EventHotKeyID        gMyHotKeyID;
    EventTypeSpec        eventType;

    eventType.eventClass = kEventClassKeyboard;
    eventType.eventKind = kEventHotKeyPressed;

    InstallApplicationEventHandler(&MXHotKeyHandler, 1, &eventType, NULL, NULL);

    gMyHotKeyID.signature = 'capk';
    gMyHotKeyID.id = 1;

    // cmd + shift + x
    RegisterEventHotKey(7, cmdKey + shiftKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}

上面的示例中, 我们注册了 ⌘ + ⇧ + X 为热键。X 的代码为 7, 其它键码可以在 Carbon/Frameworks/HlToolbox/Events.h 中查询。

Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系