NSEvent keyCode card for virtual key code

NSEvent keyCode provides a keyboard scan code, which is a hardware code representing a physical key. I want to convert the scan code to a virtual key code, which is a logical key based on the user's keyboard layout (QWERTY, AZERTY, etc.).

On Windows, I can do this through MapVirtualKey . What is the equivalent of OS X?

+6
source share
2 answers

The virtual key code is not exactly based on the user's keyboard layout. It indicates which key was pressed, and not which character the key will issue, and how it is marked.

For example, kVK_ANSI_A (from Carbon / HIToolbox / Events.h, value 0x00 ) does not mean the key that creates the character "A", it means that the key is in the position where "A 'is in the standard ANSI keyboard. If you use the layout french keyboard, this key will produce β€œQ.” If the physical keyboard is a french keyboard, this key will probably also be labeled β€œQ”.

So, a virtual key code sort is similar to a scan code, but with an idealized standard keyboard. This, as noted, is hardware independent. It also does not depend on the keyboard layout.

To translate from a virtual key code to a character, you can use UCKeyTranslate() . You need the uchr data for the current keyboard layout. You can get this using TISCopyCurrentKeyboardLayoutInputSource() and then TISGetInputSourceProperty() with kTISPropertyUnicodeKeyLayoutData as the property key.

You also need a keyboard type code. I believe that it still supports using LMGetKbdType() to get this, although it is no longer documented except in the previous section. If you don't like this, you can get a CGEvent from NSEvent , create a CGEventSource using CGEventCreateSourceFromEvent() and then use CGEventSourceGetKeyboardType() and call CGEventGetIntegerValueField() with kCGKeyboardEventKeyboardType to get the keyboard type.

Of course, it’s much simpler to just use -[NSEvent characters] or -[NSEvent charactersIgnoringModifiers] . Or, if you are implementing a text view, send the events with the key to -[NSResponder interpretKeyEvents:] (as described in the Cocoa Event Handbook: Handling Key Events ) or -[NSTextInputContext handleEvent:] (as discussed in the Cocoa Text Architecture Guide : text editing ). Any of them will go to the presentation using the appropriate action selector, for example moveBackward: or using -insertText: if a keypress (in the context of recent events and the input source) created text.

+16
source

According to the NSEvent documentation, -[NSEvent keyCode] returns a device-independent virtual key code.

+1
source

Source: https://habr.com/ru/post/952383/


All Articles