How to use UCKeyTranslate

亡梦爱人 提交于 2019-12-04 07:47:33

For kTISPropertyUnicodeKeyLayoutData, TISGetInputSourceProperty() returns a CFDataRef. You need to get its bytes pointer and treat that as the pointer to UCKeyboardLayout. I don't think that's what you're doing with this line:

var layout = UnsafeMutablePointer<UCKeyboardLayout>(ptrLayout)

I don't really know Swift, but it would probably work as:

var layout = UnsafePointer<UCKeyboardLayout>(CFDataGetBytePtr(ptrLayout))

or maybe:

var layout = CFDataGetBytePtr(ptrLayout) as UnsafePointer<UCKeyboardLayout>

Also, kUCKeyActionDisplay is mostly useless. Its intent is to return the label of the key, but it doesn't even do that reliably. You probably want to use kUCKeyActionDown.

For the modifiers, you want to use the Carbon-era shiftKey bit mask shifted right 8 bits (as shown in the documentation for UCKeyTranslate()). shiftKey is 1 << 9, so shiftKey >> 8 is 1 << 1.

For the options, you should be able to use kUCKeyTranslateNoDeadKeysMask for simplicity. It's equivalent to 1 << kUCKeyTranslateNoDeadKeysBit.

Yes, 0 is the proper value for deadKeyState for an initial keystroke or one where you don't want to apply any previous dead-key state.

I'm not sure why you've commented the maxStringLength line with uint32. That type is completely unrelated to the maximum string length. maxStringLength is the maximum number of UTF-16 code units (what the APIs incorrectly call "characters") the UCKeyTranslate() should write to the provided buffer. It's basically the buffer size, measured in UniChars (not bytes). In your case it should be 255. Or, since you probably don't expect to get 255 "characters" from a single keystroke, you could reduce the size of the buffer and set maxStringLength to match whatever it is.

Your handling of str is strange. You construct it from the unicodeString buffer before calling UCKeyTranslate(). Do you expect that string object's value to be changed because UCKeyTranslate() changes the contents of unicodeString? It does not. If it did, that would be a very bad bug in NSString. You should construct the NSString from the buffer after UCKeyTranslate() has successfully populated that buffer. Of course, you should pass actualStringLength as the length parameter when constructing the NSString.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!