Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept a hot key in Cocoa when the application window is not active

I am trying to create a utility that doesn't open a window when executed, and that would be activated from a hot key; I read that currently Cocoa doesn't have a function for that, and that I should use a deprecated Carbon function.

Isn't there really a way to use global hot keys in Cocoa? What should I do: wait for Cocoa to introduce a function for that, or use the carbon function until a similar function is not introduced in Cocoa?

like image 492
apaderno Avatar asked Dec 16 '09 14:12

apaderno


2 Answers

Use the Carbon Event Manager's RegisterEventHotKey function. This function is supported in 64-bit (notice that it lacks the “not available in 64-bit” availability note).

Conversely, NSEvent's new addGlobalMonitorForEventsMatchingMask:handler: method in Snow Leopard is not the easiest way to implement a hot-key. For one thing, it requires that the user have access for assistive devices turned on; moreover, it requires you to examine every event yourself, as compared with the RegisterEventHotKey system, which only calls your callback function when the user presses the specific key you registered for.

like image 76
Peter Hosey Avatar answered Nov 03 '22 00:11

Peter Hosey


Take a look at Shortcut Recorder (http://wafflesoftware.net/shortcut/) a framework that uses the Carbon Event Manager for Global Hotkeys it also allows you to change the user to change the HotKey (if this is what you want).

And see this Project/Code on how to implement it : http://github.com/sdegutis/SDGlobalShortcuts.

like image 21
Joshua Avatar answered Nov 03 '22 00:11

Joshua