Can't send_keys to the background window. Error : AttributeError: Neither GUI element (wrapper) nor wrapper method 'send_keys' were found (typo?)

Viewed 2077

I want to simulate keyboard stroke to a app in backboard and trying to use pywinauto to do that although I can connect to the window but when I use send_keys or keyboard.send_keys, I will show the error

    M.keyboard.send_keys('{a down}')
  File "C:\Users\Hank\anaconda3\lib\site-packages\pywinauto\application.py", line 180, in __call__
    raise AttributeError("Neither GUI element (wrapper) " \
AttributeError: Neither GUI element (wrapper) nor wrapper method 'send_keys' were found (typo?)

below is my code I try to find some answer in google but see the same issue, so come here to ask question.

import win32gui
from pywinauto.application import Application
from pywinauto.keyboard import send_keys, KeySequenceError
import win32process

def get_window_pid(title):
    hwnd = win32gui.FindWindow(None, title)
    threadid,pid = win32process.GetWindowThreadProcessId(hwnd)
    return pid

hwnd = get_window_pid('Greedy snake')
print(hwnd)
M=app.connect(process=hwnd)
form = app.window(title_re="Greedy snake")
while True:
    sleep(2)

    form.keyboard.send_keys('{a down}')
    form.keyboard.send_keys('{a up}')
1 Answers

This is completely wrong usage of pywinauto and a lot of unnecessary code. keyboard is a module, it's not attribute of form (the error message tells the element with name="keyboard" is not found, of course!). Use this code:

from pywinauto import Application

app = Application(backend="win32").connect(title_re="Greedy snake", timeout=10)
form = app.window(title_re="Greedy snake")
form.type_keys('{a down}')
form.type_keys('{a up}')

It's worth careful reading the docs about pywinauto starting from this: https://pywinauto.readthedocs.io/en/latest/getting_started.html, then this: https://pywinauto.readthedocs.io/en/latest/wait_long_operations.html

Related