2016-02-19 143 views
1

我尝试用python模拟键盘,我不知道如何处理多个键盘按钮按下。下面的代码工作在同一时间(FE“CTRL + C”)按1个或2键完美的罚款:有没有办法在python中动态创建/修改函数

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楼或更多的按钮?什么是最优雅的方式来做到这一点?如果'+'count == 2,如果'+'count == 3等,我可以添加,如果'+'count == 2,但必须有更好的方法来做到这一点。我希望我的函数能够适应参数的数量。

例如:

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()) 
+1

是[this](http://stackoverflow.com/questions/3394835/args-and-kwargs)你需要什么? – JETM

+0

编号我已经使用了参数,我希望函数根据分割后列表中有多少个参数进行更改。如果我想同时按下按钮,我必须在单个SendInput(Keyboard()语句中使用它们,就像你上面看到的那样,这个if语句已经在函数中了。 – Gunnm

回答

1

我不熟悉您正在使用,所以我假设他们是定制的SendInput /键盘的东西并由你撰写。

假设SendInput就像def SendInput(*args)定义(由@JETM的建议),并说明:last_arg实际上应该current_arg,你应该能够这样称呼它:

arglist = current_arg.split('+') 
# This will create a list of Keyboard objects 
keys = [KeyBoard(globals()["VK_%s" % key.upper()]) for key in arglist] 
# *keys splits the list of Keyboard objects so that SendInput receives 
# one entry in it's argument list for each Keyboard object in keys 
SendInput(*keys) 

利用这一点,内SendInput的ARGS变量将是每个键有一个Keyboard对象的列表。

+0

它工作的很好,谢谢你的帮助。 – Gunnm

相关问题