How to implement shortcut input in Mac Cocoa App?

I need to create a global hotkey input field in my Cocoa application.

I know about Shortcut Recorder, but this is a very old solution. It has parts implemented using Carbon, which is deprecated, and I cannot publish my application on the Mac App Store if I use it.

Is there a modern solution ready to use? Can someone give me a way to do this myself (I don't know where to start)?

+7
source share
3 answers

There is a modern infrastructure called MASShortcut for implementing global shortcuts in OS X 10.7 +.

+14
source

On Mac OS X 10.6 and later, you can use the + addGlobalMonitorForEventsMatchingMask: handler: and + addLocalMonitorForEventsMatchingMask: handler methods: defined from the NSEvent class. Event monitoring reports the following information:

Local and global event monitors are mutually exclusive. For example, the global monitor does not track the event flow of the application in which it is installed. In the local event monitor, only the application event flow is observed. To track events from all applications, including the β€œcurrent” application, you must install both event monitors.

The code shown on this page is for the local event monitor, but the code for the global event monitor is the same; what changes cause the NSEvent method.

 _eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask: (NSLeftMouseDownMask | NSRightMouseDownMask | NSOtherMouseDownMask | NSKeyDownMask) handler:^(NSEvent *incomingEvent) { NSEvent *result = incomingEvent; NSWindow *targetWindowForEvent = [incomingEvent window]; if (targetWindowForEvent != _window) { [self _closeAndSendAction:NO]; } else if ([incomingEvent type] == NSKeyDown) { if ([incomingEvent keyCode] == 53) { // Escape [self _closeAndSendAction:NO]; result = nil; // Don't process the event } else if ([incomingEvent keyCode] == 36) { // Enter [self _closeAndSendAction:YES]; result = nil; } } return result; }]; 

Once the monitor is no longer needed, you will remove it using the following code:

 [NSEvent removeMonitor:_eventMonitor]; 
+13
source

Not all Carbon are out of date. You can no longer use a pure carbon app, but some APIs work, and some of them are still the easiest way to do certain things.

One of them is the Carbon Events hotkey API. Of course, you can sift through all the events using the NSEvent event monitoring methods, but this is unnecessary work. The Carbon Events hotkey API is still supported and much simpler - you just say which key you want to map and which function to call when the key is pressed. And there are Cocoa wrappers like DDHotKey that make it even easier.

+12
source

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


All Articles