Noga
Noga

Reputation: 131

How to get Virtual-Key-Code of a key

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!

Upvotes: 2

Views: 9226

Answers (2)

Dmytro
Dmytro

Reputation: 1390

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

Upvotes: 5

Serge Ballesta
Serge Ballesta

Reputation: 148870

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.

Upvotes: 2

Related Questions