2

I am trying to write a function that will receive an ascii key and will convert it to a Virtual-key-code.

Ex:

from msvcrt import getch
key= ord(getch()) #getting the ASCII character for a key that was pressed
def(key):
   #converting the key to virtual key code

for example: the ascii code of a is 41. I want the function to receive it and return 0x41-which is the virtual key code of the key.

Thank you in advance for any help!

Noga
  • 121
  • 2
  • 8

2 Answers2

5

You can use VkKeyScan from Windows API:

from ctypes import windll

def char2key(c):
    # https://msdn.microsoft.com/en-us/library/windows/desktop/ms646329(v=vs.85).aspx
    result = windll.User32.VkKeyScanW(ord(unicode(c)))
    shift_state = (result & 0xFF00) >> 8
    vk_key = result & 0xFF

    return vk_key
Dmytro
  • 1,290
  • 17
  • 21
  • `VkKeyScan` (or `VkKeyScanEx`) do a great job but they have limits. First `a` (`'\x61'`) and `A` (`'\x41'`) have same scan code (`VK_A`) and differe only by their shift state. Next many non ASCII characters cannot be directly typed from keyboard and return a key code of -1. For example the LATIN SMALL LETTER THORN (`'รพ'` or `'\xef'`) cannot be produced on my French keyboard and `VkKeyScan` gives a scan code of -1 โ€“ Serge Ballesta May 01 '18 at 06:43
  • Yes, it seems it works not for all cases. About "First a ('\x61') and A ('\x41') have same scan code (VK_A)" it's normal, you should handle by self shift state. โ€“ Dmytro May 01 '18 at 13:03
2

Unfortunately you cannot - As you include msvcrt.h, the remaining part of the answer assumes that you use a Windows system.

There is no bijection between an ASCII code and a virtual key. For example the character "1" (ascii 0x31) can be produced by the key 1 with virtual key code 0x31 or by the numeric keypad key num 1 with virtual key code VK_NUMPAD1 or 0x61.

The best you can do is to manually build a translation table with the help of the list of the virtual key codes from the msdn and choose which key you assume for each ASCII code.

The only easy rules are that the virtual key code for upper case letters (A-Z) and numbers (0-9 but not on the numeric keypad) is the same as the ascii code.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252