How do you implement global keyboard interceptors on Mac OS X?

I know that this can be done for Windows and that XGrabKey can be used for X11, but what about Mac OS X? I want to create a class that allows you to set keyboard shortcuts that can be called even if application windows are inactive.

+4
source share
2 answers

Take a look at the addGlobalMonitorForEventsMatchingMask:handler: class methods in the addGlobalMonitorForEventsMatchingMask:handler: class. You can also find Shortcut Recorder .

+2
source

This is not supported (yet?) In Cocoa. You can still use the old Carbon library for this (which is 64 bit compatible), but unfortunately Apple decided to delete all the documentation on this.

There is a good blog article here: http://dbachrach.com/blog/2005/11/program-global-hotkeys-in-cocoa-easily/

This article is a bit long for my taste, so here is a short version:

 - (id)init { self = [super init]; if (self) { EventHotKeyRef hotKeyRef; EventHotKeyID hotKeyId; EventTypeSpec eventType; eventType.eventClass = kEventClassKeyboard; eventType.eventKind = kEventHotKeyPressed; InstallApplicationEventHandler(&mbHotKeyHandler, 1, &eventType, NULL, NULL); hotKeyId.signature = 'hotk'; hotKeyId.id = 1337; RegisterEventHotKey(kVK_ANSI_C, cmdKey + shiftKey, hotKeyCopyId, GetApplicationEventTarget(), 0, &hotKeyRef); } } OSStatus mbHotKeyHandler(EventHandlerCallRef nextHandler, EventRef event, void *userData) { // Your hotkey was pressed! return noErr; } 

A hotkey is registered when RegisterEventHotKey(…) called. In this case, it registers CMD + Shift + C.

ANSI keys are defined in HIToolbox / Events.h, so you can search for other keys there (just press CMD + Shift + O in Xcode and type Events.h to find it).

You need to do a bit more work if you need some hot keys or you want to call methods from your handler, but all this is in the link at the top of this answer.

I was looking for a simple answer to this question, so hope this helps someone else ...

+3
source

Source: https://habr.com/ru/post/987452/


All Articles