Forked from ArthurYidi/translatekeycodes.swift
Created
January 18, 2022 04:19
virtual key codes to unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static func keyCodeToString(keyCode: CGKeyCode, eventModifiers: Int) -> String? { | |
let curKeyboard = TISCopyCurrentKeyboardInputSource().takeRetainedValue() | |
let rawLayoutData = TISGetInputSourceProperty(curKeyboard, kTISPropertyUnicodeKeyLayoutData) | |
let layoutData = unsafeBitCast(rawLayoutData, to: CFData.self) | |
let keyboardLayoutPtr = unsafeBitCast(CFDataGetBytePtr(layoutData), to: UnsafePointer<UCKeyboardLayout>.self) | |
var deadKeyState: UInt32 = 0 | |
var actualStringLength = 0 | |
var unicodeString: [UniChar] = [0, 0, 0, 0] | |
let status = UCKeyTranslate(keyboardLayoutPtr, | |
keyCode, | |
UInt16(kUCKeyActionDown), | |
UInt32(eventModifiers >> 8), // from UCKeyTranslate doc | |
UInt32(LMGetKbdType()), | |
0, | |
&deadKeyState, | |
unicodeString.count, | |
&actualStringLength, | |
&unicodeString) | |
if status != noErr { | |
return nil | |
} | |
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