Skip to content

Instantly share code, notes, and snippets.

@vayn
Forked from ArthurYidi/translatekeycodes.swift
Created November 13, 2016 12:20
Show Gist options
  • Save vayn/311deff41486b5efb1d3933a369cf6ec to your computer and use it in GitHub Desktop.
Save vayn/311deff41486b5efb1d3933a369cf6ec to your computer and use it in GitHub Desktop.
virtual key codes to unicode characters
func keyCodeToString(keyCode: CGKeyCode) -> String {
let curKeyboard = TISCopyCurrentKeyboardInputSource().takeRetainedValue()
let ptr = TISGetInputSourceProperty(curKeyboard, kTISPropertyUnicodeKeyLayoutData)
let keyboardLayoutPtr = UnsafePointer<UCKeyboardLayout>(ptr)
var deadKeyState: UInt32 = 0
var actualStringLength = 0
var unicodeString = [UniChar](count: 255, repeatedValue: 0)
let status = UCKeyTranslate(keyboardLayoutPtr,
keyCode,
UInt16(kUCKeyActionDown),
0,
UInt32(LMGetKbdType()),
0,
&deadKeyState,
255,
&actualStringLength,
&unicodeString)
print("Status Error: \(status != noErr)")
print("Param Error: \(status == Int32(paramErr))")
return NSString(characters: unicodeString, length: actualStringLength) as String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment