您好我已经编写了这段代码,但正如您在最后看到的那样,使用每个密钥执行此操作并不理想:
if (ThatKey == "e"):
ThatKey = E_KEY
有更有效的方法吗?
(完整代码): https://pastebin.com/ctnYVjxN
答案 0 :(得分:0)
问题本身与 ctypes 无关(事实上它在代码中使用了它无关紧要),所以我删除了标签。
AFAIK 虚拟密钥代码与其密钥名称之间没有映射(如果可以的话)。我们来考虑VK_RETURN
。 Enter 键有很多名称:
拥有这样的映射是没有意义的,因为总是需要进行更改。因此,任何需要映射的人都必须手动编写#34;。
code.py :
import sys
VK_TAB = 0x09
VK_MENU = 0x12
VK_RETURN = 0x0D
VK_F1 = 0x70
VK_ESCAPE = 0x1B
# Some other VK_* keys
INVALID_VK = 0
SPECIAL_KEYS = {
"ENTER": VK_RETURN,
"ESC": VK_ESCAPE
}
def get_virtual_key_code(key_name, module=None, special_keys_mapping=None):
key_name_upper = key_name.upper()
if key_name.isalnum() and len(key_name) == 1:
return ord(key_name_upper)
vk_code_name = "VK_" + key_name_upper
if module is None:
vk_code = globals().get(vk_code_name, INVALID_VK)
else:
vk_code = getattr(module, vk_code_name, INVALID_VK)
if vk_code == INVALID_VK and special_keys_mapping:
vk_code = special_keys_mapping.get(key_name_upper, INVALID_VK)
return vk_code
def main():
vkc = None
while vkc != VK_ESCAPE:
key_name = raw_input("What key would you like to press: ")
vkc = get_virtual_key_code(key_name, special_keys_mapping=SPECIAL_KEYS)
print("Virtual key code for '{:s}': 0x{:02X}".format(key_name, vkc))
print("Done.")
if __name__ == "__main__":
print("Python {:s} on {:s}\n".format(sys.version, sys.platform))
main()
备注强>:
get_virtual_key_code
:
key_name
:它是关键字的字符串表示module
:定义 VK _ * 常量的模块。现在。它们位于当前模块的全局部分。但是,如果您决定将它们移动到一个单独的模块(我建议,为了保持模块化),只需将其作为参数传递(当然,在导入之后)。此外,您可以从函数中删除2 nd if
(仅保留正确的分支)key_name
是字母数字字符之一,则其虚拟代码是 ASCII 代码(字母大写)。因此,无需定义相应的 VK _ * 常量(或任何其他常量,如E_KEY
)VK_F1
)special_keys_mapping
- 如果提供)。这适用于特殊情况(例如 ENTER - VK_RETURN
,因为没有自动链接方式)VK_ESCAPE
raw_input
替换input
)<强>输出强>:
(py27x64_test) e:\Work\Dev\StackOverflow\q050638652>"e:\Work\Dev\VEnvs\py27x64_test\Scripts\python.exe" code.py Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 What key would you like to press: 1 Virtual key code for '1': 0x31 What key would you like to press: a Virtual key code for 'a': 0x41 What key would you like to press: A Virtual key code for 'A': 0x41 What key would you like to press: Virtual key code for ' ': 0x00 What key would you like to press: f1 Virtual key code for 'f1': 0x70 What key would you like to press: f2 Virtual key code for 'f2': 0x00 What key would you like to press: return Virtual key code for 'return': 0x0D What key would you like to press: Enter Virtual key code for 'Enter': 0x0D What key would you like to press: ESC Virtual key code for 'ESC': 0x1B Done.