老谭笔记

在Mac OSX中注册自定义的快捷键

在Mac OSX系统的开发中,我们除了可以让按钮、菜单拥有特定的快捷键之外,我们还可以注册全局的快捷键,即当前程序不处于活跃状态中也能收到的快捷键事件响应。下面帖上代码:

diannao_64b

##定义注册快捷键需要保存的变量和回调方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//用于保存快捷键事件回调的引用,以便于可以注销
static EventHandlerRef g_EventHandlerRef = NULL;
//用于保存快捷键注册的引用,便于可以注销该快捷键
static EventHotKeyRef a_HotKeyRef = NULL;
static EventHotKeyRef b_HotKeyRef = NULL;
//快捷键注册使用的信息,用在回调中判断是哪个快捷键被触发
static EventHotKeyID a_HotKeyID = {'keyA',1};
static EventHotKeyID b_HotKeyID = {'keyB',2};
//快捷键的回调方法
OSStatus myHotKeyHandler(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void *inUserData)
{
//判定事件的类型是否与所注册的一致
if (GetEventClass(inEvent) == kEventClassKeyboard && GetEventKind(inEvent) == kEventHotKeyPressed)
{
//获取快捷键信息,以判定是哪个快捷键被触发
EventHotKeyID keyID;
GetEventParameter(inEvent,
kEventParamDirectObject,
typeEventHotKeyID,
NULL,
sizeof(keyID),
NULL,
&keyID);
if (keyID.id == a_HotKeyID.id) {
NSLog(@"pressed:shift+command+A");
}
if (keyID.id == b_HotKeyID.id) {
NSLog(@"pressed:option+B");
}
}
return noErr;
}

##在程序启动后注册快捷键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
//先注册快捷键的事件回调
EventTypeSpec eventSpecs[] = {{kEventClassKeyboard,kEventHotKeyPressed}};
InstallApplicationEventHandler(NewEventHandlerUPP(myHotKeyHandler),
GetEventTypeCount(eventSpecs),
eventSpecs,
NULL,
&g_EventHandlerRef);
//注册快捷键:shift+command+A
RegisterEventHotKey(kVK_ANSI_A,
cmdKey|shiftKey,
a_HotKeyID,
GetApplicationEventTarget(),
0,
&a_HotKeyRef);
//注册快捷键:option+B
RegisterEventHotKey(kVK_ANSI_B,
optionKey,
b_HotKeyID,
GetApplicationEventTarget(),
0,
&b_HotKeyRef);
}

在程序结束的时候注销快捷键

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)applicationWillTerminate:(NSNotification *)notification
{
//注销快捷键
if (a_HotKeyRef)
{
UnregisterEventHotKey(a_HotKeyRef);
a_HotKeyRef = NULL;
}
if (b_HotKeyRef)
{
UnregisterEventHotKey(b_HotKeyRef);
b_HotKeyRef = NULL;
}
//注销快捷键的事件回调
if (g_EventHandlerRef)
{
RemoveEventHandler(g_EventHandlerRef);
g_EventHandlerRef = NULL;
}
}

运行程序,当按下shift+command+A或option+B的快捷键后,你便会在控制台看到相应的打印输出了!