Search code examples
windowsx11xlib

how do I convert XLib keycode to microsoft virtual key?


How do I convert the X11 keycode to a microsoft virtual key code

int processKeyboardMessage( XEvent *event )
{
  assert( KeyPress == event->type );

  //TODO: Before returning convert keycode into microsoft virtual key code     
  return ( event->xkey.keycode );
}

Solution

  • One option is to make enums for all of the possible keys on every platform. Then you can deal with keycodes in the application in the system's native format. There are some subtle things you need to do to work around certain situations (like left/right alt on win32), but you can implement these special cases and update your enum for them. Rather than creating large tables or switch-case statements on every platform.

    /* my_key.h : creates names for key codes on Windows and X11 */
    #ifndef MY_KEY_H
    #define MY_KEY_H
    #if defined(_WIN32)
    #include <windows.h>
    enum my_key {
        MY_KEY_BACKSPACE = VK_BACK,
        MY_KEY_RETURN = VK_RETURN,
        MY_KEY_LEFT = VK_LEFT,
        MY_KEY_RIGHT = VK_RIGHT,
        MY_KEY_DOWN = VK_DOWN,
        MY_KEY_UP = VK_UP,
        /* TODO: define the rest of the keys */
    };
    #else defined(__APPLE__)
    enum my_key {
        MY_KEY_BACKSPACE = 0x33,
        MY_KEY_RETURN = 0x24,
        MY_KEY_LEFT = 0x7b,
        MY_KEY_RIGHT = 0x7c,
        MY_KEY_DOWN = 0x7d,
        MY_KEY_UP = 0x7e,
        /* TODO: define the rest of the keys */
    };
    #else /* assume X11 */
    #include <X11/keysym.h>
    enum my_key {
        MY_KEY_BACKSPACE = XK_BackSpace,
        MY_KEY_RETURN = XK_Linefeed,
        MY_KEY_LEFT = XK_Left,
        MY_KEY_RIGHT = XK_Right,
        MY_KEY_DOWN = XK_Down,
        MY_KEY_UP = XK_Up,
        /* TODO: define the rest of the keys */
    };
    #endif
    #endif