keycode to string?

Mac OSX specific forum
Rinzwind
Enthusiast
Enthusiast
Posts: 638
Joined: Wed Mar 11, 2009 4:06 pm
Location: NL

keycode to string?

Post by Rinzwind »

Trying to translate code from https://stackoverflow.com/questions/191 ... -cgkeycode and as happens, stuck...

Code: Select all

EnableExplicit

ImportC ""
  TISCopyCurrentKeyboardInputSource()
  TISGetInputSourceProperty(keyboard, layout)
  UCKeyTranslate(*UCKeyboardLayout,  UInt16virtualKeyCode, UInt16keyAction, UInt32modifierKeyState, UInt32keyboardType,
                 OptionBitskeyTranslateOptions, *UInt32deadKeyState,  UniCharCountmaxStringLength,  *UniCharCountactualStringLength,
                 UniCharunicodeString)    
  LMGetKbdType()
  CFStringCreateWithCharacters(alloc, *chars, numChars);
  CFRelease(obj)
  CFStringGetCharacters(theString, location, length, *buffer)
EndImport

Procedure.s CFStringGetString(theString)
  Protected Length.i = CFStringGetLength_(theString)
  Protected Dim Buffer.u(Length)
  CFStringGetCharacters(theString, 0, Length, @Buffer())
  ProcedureReturn PeekS(@Buffer())
EndProcedure

Procedure kOS(constant.s)
  Protected t
  t = dlsym_(#RTLD_DEFAULT, constant)
  If t
    t = PeekI(t)
  Else
    Debug "! " + constant + " not found"
  EndIf
  ProcedureReturn t
EndProcedure

Global kTISPropertyUnicodeKeyLayoutData = kOS("kTISPropertyUnicodeKeyLayoutData")
#kUCKeyActionDisplay = 3
#kUCKeyTranslateNoDeadKeysBit = 0

Procedure KeyCodeToString(keyCode)
  Protected currentKeyboard = TISCopyCurrentKeyboardInputSource()
  Protected layoutData = TISGetInputSourceProperty(currentKeyboard, kTISPropertyUnicodeKeyLayoutData)
  Protected Dim chars.u(4)
  Protected keysDown.l
  Protected realLength.l
  UCKeyTranslate(layoutData,
                 keyCode,
                 #kUCKeyActionDisplay,
                 0,
                 LMGetKbdType(),
                 #kUCKeyTranslateNoDeadKeysBit,
                 @keysDown,
                 4,
                 @realLength,
                 @chars())
  CFRelease(currentKeyboard)
  Protected cfs = CFStringCreateWithCharacters(#kCFAllocatorDefault, @chars(), 1)
  Debug CFStringGetString(cfs)
EndProcedure

Debug KeyCodeToString(8) ;c
Any idea how to make it output "c" or better code/option?

EDIT
Adding uchr = CFDataGetBytePtr(layoutData) and using uchr in the UCKeyTranslate call works. Hope its stable too...