Reputation: 57
for the last two days I've been searching and reading a lot about something that should be very simple. It has become clear that isn't the case: I'm trying to make this:
That's all. I know shortcut recorder is pretty old and I've been working with the Demo of MASShortcut. MASShortcut is pretty awesome, but it's a lot of code for something so seemingly easy.
I've also searched in a lot of Apple sample code (hoping they would implement this somewhere other than Interface Builder, but no luck so far).
This leaves me with the following questions:
-Is there any documentation that could clarify some of this stuff? Or are there other, more simple solutions than MASShortcut?
-I've been trying to replicate something like the IB control myself, but I'm still stuck at "converting" the pressed keys to characters in the NSTextField (or is it a custom NSView in IB?). Does Apple offer an easy way to do this? Because catching everything with sendEvent and comparing it against a list of all keys seems a lot of work and I wonder how the apple programmers have done that in the control seen above. Should that be the only solution, are there different keyboard layouts I should be concerned about when I use it?
-How do other applications implement this so that it becomes visible here:
As you can see TextWranglers appears here, does that happen automatically when I call "[NSEvent addGlobalMonitorForEventsMatchingMask:]" in my application?
These are a lot of questions, I'm just hoping one of you guys can point me in the right direction.
Thanks in advance, Frans
Upvotes: 1
Views: 357
Reputation: 64022
I was fiddling around with getting characters from key presses myself last week, and I stumbled upon two functions that for some reason I hadn't seen before: UCKeyTranslate()
in CoreServices and the apparently related CGEventKeyboardGetUnicodeString()
(looks like a wrapper of the former) in ApplicationServices.
It seems like these are the functions -- or at least go through to the code -- that Apple's own text system is using to translate key presses into Unicode strings for display as text.
A simple examination of an NSEvent
's modifierFlags
should suffice for turning the modifier key state into a string like ⌥⇧⌘:
NSUInteger flags = [theEvent modifierFlags];
NSString * modString = [NSString stringWithFormat:@"%@%@%@%@",
(flags & NSControlKeyMask) ? @"^" : @"",
(flags & NSAlternateKeyMask) ? @"⌥" : @"",
(flags & NSShiftKeyMask) ? @"⇧" : @"",
(flags & NSCommandKeyMask) ? @"⌘" : @""];
You might also want to have a look at Allan Odgaard's blog post "Deciphering an NSEvent" about the heuristic he developed for deciding what keys were being pressed.
Upvotes: 3