Jul. 14th, 2024
2024年 6月 9日

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'; = 1;

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

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

Pinned Message
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF