RE: Key number to Unicode string (email@hidden)
RE: Key number to Unicode string (email@hidden)
- Subject: RE: Key number to Unicode string (email@hidden)
- From: "Dorian Johnson" <email@hidden>
- Date: Thu, 7 Jun 2007 22:48:57 -0500
If it's a cocoa app, in the keyDown, use the -[NSEvent characters] method.
Otherwise, check out this bit of code I wrote a while back. It's got some
extra stuff you probably don't need (composing detection, etc) but it should
be easy to filter that out. The code was briefly used in a release version,
but it's not been extensively tested.
This works with unicode (uchr) and roman (kchr) keyboards.
- (void)handleKeyEvent:(NSEvent *)ev keyDown:(BOOL)down
{
static UInt32 deadKeyState = 0, keyTranslateState = 0, initialized = 0;
static SInt32 lastKeyLayoutID = 0;
UCKeyboardLayout *uchrData;
void *KCHRData;
SInt32 keyLayoutKind, keyLayoutID;
KeyboardLayoutRef keyLayout;
UInt32 charCode;
UniCharCount actualStringLength;
UniChar unicodeString[4];
unsigned char code1, code2;
uint16 uniChar = 0;
BOOL composing = YES;
UInt16 keyCode = [ev keyCode], kchrKeyCode;
unsigned int mods = [ev modifierFlags];
KLGetCurrentKeyboardLayout(&keyLayout);
KLGetKeyboardLayoutProperty(keyLayout, kKLKind, (const void
**)&keyLayoutKind);
KLGetKeyboardLayoutProperty(keyLayout, kKLIdentifier, (const
void**)&keyLayoutID);
if (lastKeyLayoutID != keyLayoutID || !initialized) {
deadKeyState = keyTranslateState = 0;
initialized = 1;
lastKeyLayoutID = keyLayoutID;
}
if (keyLayoutKind == kKLKCHRKind)
{
kchrKeyCode = (keyCode & 0x7f) | (mods & 0xffff00ff); // this might
have a slight logic error in it. be careful, test it first
kchrKeyCode = (down) ? (kchrKeyCode & 0xff7f) : (kchrKeyCode |
0x80); // this too
KLGetKeyboardLayoutProperty(keyLayout, kKLKCHRData, (const void
**)&KCHRData);
charCode = KeyTranslate(KCHRData, kchrKeyCode, &keyTranslateState);
// ignore code1, it's normally gibberish
//code1 = (charCode & 0xff0000) >> 16;
code2 = (charCode & 0xff);
if (keyTranslateState == 0 && code2 != '\0') {
// This character is finished composing and should be sent
const char chrs[2] = {code2, '\0'};
uniChar = [[NSString stringWithCString:chrs]
characterAtIndex:0]; // I don't remember why this is used, there's probably
a reason
composing = NO;
}
}
else
{
KLGetKeyboardLayoutProperty(keyLayout, kKLuchrData, (const void
**)&uchrData);
UCKeyTranslate(uchrData, keyCode, kUCKeyActionDown, mods,
LMGetKbdType(), 0, &deadKeyState,
4, &actualStringLength, unicodeString);
if (deadKeyState == 0 || deadKeyState == 65536) {
// This character is finished composing and should be sent
uniChar = unicodeString[0];
composing = NO;
}
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden