Here you can take a series of key click events and get the Unicode characters that they typed.
Basically, call UCKeyTranslate () for each received keystroke event. Use its argument deadKeyStateto capture the dead key and pass it in for later recall.
Example:
- Get a keypress event for the -e option.
- Call
UCKeyTranslate()using the virtual key code (for e), the state of the modifier key (for the option) and the variable to save the state of the dead key. - e.
UCKeyTranlate() key code ( e) , .
( ):
CFStringRef getCharactersForKeyPress(NSEvent *event, UInt32 *deadKeyState)
{
TISInputSourceRef currentKeyboard = TISCopyCurrentKeyboardInputSource();
CFDataRef layoutData = TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData);
const UCKeyboardLayout *keyboardLayout = (const UCKeyboardLayout *)CFDataGetBytePtr(layoutData);
CGEventFlags flags = [event modifierFlags];
UInt32 modifierKeyState = (flags >> 16) & 0xFF;
const size_t unicodeStringLength = 4;
UniChar unicodeString[unicodeStringLength];
UniCharCount realLength;
UCKeyTranslate(keyboardLayout,
[event keyCode],
kUCKeyActionDown,
modifierKeyState,
LMGetKbdType(),
0,
deadKeyState,
unicodeStringLength,
&realLength,
unicodeString);
CFRelease(currentKeyboard);
return CFStringCreateWithCharacters(kCFAllocatorDefault, unicodeString, realLength);
}