Registering global hot keys with Cocoa and Objective-C----------------NDHotKeyEvent

In your application’s controller add the following:

- (void)awakeFromNib
{
	[self registerHotKeys];
}

And the following code which registers the hot keys:

-(void)registerHotKeys
{	
    EventHotKeyRef gMyHotKeyRef;
    EventHotKeyID gMyHotKeyID;
    EventTypeSpec eventType;
    eventType.eventClass=kEventClassKeyboard;
    eventType.eventKind=kEventHotKeyPressed;	
	
    InstallApplicationEventHandler(&OnHotKeyEvent, 1, &eventType, (void *)self, NULL);
	
    gMyHotKeyID.signature='htk1';
    gMyHotKeyID.id=1;
    RegisterEventHotKey(20, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);	
	
    gMyHotKeyID.signature='htk2';
    gMyHotKeyID.id=2;	
    RegisterEventHotKey(21, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);	
	
    gMyHotKeyID.signature='htk3';
    gMyHotKeyID.id=3;	
    RegisterEventHotKey(23, cmdKey+optionKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);	
}

OSStatus OnHotKeyEvent(EventHandlerCallRef nextHandler,EventRef theEvent,void *userData)
{
    EventHotKeyID hkCom;
	
    GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hkCom), NULL, &hkCom);
    AppController *controller = (AppController *)userData;	
	
    int l = hkCom.id;
	
    switch (l) {
        case 1: 		
			NSLog(@"Capture area");	
			[ScreenCapture captureArea:controller];
			break;
        case 2: 
			NSLog(@"Capture screen");	
			[ScreenCapture captureScreen:controller];
			break;
        case 3: 
			NSLog(@"Capture window");	
			[ScreenCapture captureWindow:controller];
			break;  
    }

    return noErr;
}

The code used in this snippet was inspired by this blog post http://dbachrach.com/blog/2005/11/28/program-global-hotkeys-in-cocoa-easily/

Alternatives

If you need a more complete solution you can use one of these open-source alternatives:

Showing the application window

Usually you want to show the application window when the hot key is pressed. This can be done as explained in this snippet

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值