如何使用 Python 模拟字符串键盘输入? [英] How to simulate string keyboard input using Python?
问题描述
我使用的是 windows 8 并且有 windows api 模块
我正在尝试创建一个方法:
TypeInput(argument) #argument 是一个字符串
如果参数是字符串,我的方法会模拟参数的输入.
不幸的是,
我目前使用以下方法模拟打字:
win32api.keybd_event(win32con.KEYCODE, MS KEYCODE, 0, 0)
而且我不知道如何抽象它以便我可以插入任意字符.
我最初的猜测是做 unicode
转换
但似乎问题更糟,例如
ord('f') = 102 = 66 十六进制
但是'f'的Windows代码是
0x046
46 不是 66...
所以我不确定它们是如何转换的,它似乎不是等距的.
此时我得出的结论是有一种更优雅的方法来做到这一点.
会不会有人太棒了,给我看并解释?
您想使用 SendInput
,而不是 keybd_event,并确保 KEYBDINPUT.dwFlags
字段具有 KEYEVENTF_UNICODE
标志设置.如果您没有使用KEYEVENTF_UNICODE
,那么您必须确保同时设置扫描码和键码;否则,您将遇到特定于应用的故障.
SendInput 有一个 Python 包装器,所以这也有帮助.>
I'm using windows 8 and have the windows api module
I am trying to create a method:
TypeInput(argument) #argument is a string
with the objective that my method simulates the typing of the argument if the argument is a string.
Unfortunately,
I currently simulate typing using:
win32api.keybd_event(win32con.KEYCODE, MS KEYCODE, 0, 0)
And i don't know how to abstract this so that I can plug in arbitrary characters.
My initial guess was to do unicode
conversions
but it seems the problem is worse for example
ord('f') = 102 = 66 in hex
but the Windows code for 'f' is
0x046
and 46 isn't 66...
so i'm not really sure how they are converting, It doesn't seem to be equally spaced.
At this point i have come to the conclusion there is a more elegant way to do it.
Would someone be so awesome as to show me it and explain?
You want to use SendInput
, rather than keybd_event, and make sure that the KEYBDINPUT.dwFlags
field has the KEYEVENTF_UNICODE
flag set. If you're not using KEYEVENTF_UNICODE
, then you have to make sure to set both the scan code and the key code; otherwise you will get app-specific failures.
There is a Python wrapper for SendInput, so that will help too.
这篇关于如何使用 Python 模拟字符串键盘输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!