How to get Virtual-Key-Code of a key

坚强是说给别人听的谎言 提交于 2019-12-25 05:20:40

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/43753346/how-to-get-virtual-key-code-of-a-key

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