1

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())
4

1 に答える 1

1

私はあなたが使用している SendInput/Keyboard に精通していないので、それらはカスタムであり、あなたによって書かれたものであると想定しています。

SendInput@JETM で提案されているように定義されており、last_arg が実際には current_arg であると仮定すると、次のdef SendInput(*args)ように呼び出すことができるはずです。

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 変数は、キーごとに 1 つの Keyboard オブジェクトを含むリストになります。

于 2016-02-19T18:54:32.770 に答える