【发布时间】:2016-02-19 18:19:00
【问题描述】:
我尝试用 python 模拟键盘,但我不知道如何处理多个键盘按钮按下。下面的代码可以在同时按下 1 或 2 个键(fe 'ctrl + c')时完美运行:
if '+' in current_arg:
current_arg = current_arg.split('+')
current_arg[0] = current_arg[0].strip()
current_arg[1] = current_arg[1].strip()
SendInput(Keyboard(globals()["VK_%s" % current_arg[0].upper()]),
Keyboard(globals()["VK_%s" % current_arg[1].upper()]))
time.sleep(input_time_down())
if len(last_arg) > 1 and type(last_arg) == list:
SendInput(Keyboard(globals()["VK_%s" % last_arg[0].upper()], KEYEVENTF_KEYUP),
Keyboard(globals()["VK_%s" % last_arg[1].upper()], KEYEVENTF_KEYUP))
time.sleep(input_time_down())
else:
SendInput(Keyboard(globals()["VK_%s" % last_arg.upper()], KEYEVENTF_KEYUP))
time.sleep(input_time_down())
但是如果同时按下 3 个或更多按钮怎么办?最优雅的方法是什么?我可以添加 if '+' count == 2、if '+' count == 3 等,但必须有更好的方法来做到这一点。我希望我的函数能够适应参数的数量。
例如:
keyboard_sim('ctrl + shift + esc'):
if '+' in current_arg:
current_arg = current_arg.split('+')
current_arg[0] = current_arg[0].strip()
### function adds another current_arg for each argument
current_arg[1] = current_arg[1].strip()
current_arg[2] = current_arg[2].strip()
SendInput(Keyboard(globals()["VK_%s" % current_arg[0].upper()]),
### function adds another Keyboard for each argument
Keyboard(globals()["VK_%s" % current_arg[1].upper()]))
Keyboard(globals()["VK_%s" % current_arg[2].upper()]))
time.sleep(input_time_down())
if len(last_arg) > 1 and type(last_arg) == list:
### function adds another Keyboard KEYEVENTF for each argument
SendInput(Keyboard(globals()["VK_%s" % last_arg[0].upper()], KEYEVENTF_KEYUP),
Keyboard(globals()["VK_%s" % last_arg[1].upper()], KEYEVENTF_KEYUP))
Keyboard(globals()["VK_%s" % last_arg[2].upper()], KEYEVENTF_KEYUP))
time.sleep(input_time_down())
else:
### this is added so I won't get error if there is single key pressed
SendInput(Keyboard(globals()["VK_%s" % last_arg.upper()], KEYEVENTF_KEYUP))
time.sleep(input_time_down())
【问题讨论】:
-
你需要this吗?
-
没有。我已经使用了 args 我希望函数根据拆分后列表中的参数数量来更改。如果我想同时按下按钮,我必须像上面看到的那样在单个 SendInput(Keyboard() 语句中使用它们。这个 if 语句已经在函数中。