Search code examples
pythonpython-3.xautomationpywin32pywinauto

Send keys to background application


I am trying to send keys to an application running in the background. I want to send 'Alt+f+a' to the background application. I tried type_keys('%fa') from pywinauto but that brings the window to the foreground, I want it to remain in the background.

Here is a bit of what I currently have:

app = Application(backend="win32").connect(path=exePath)

# Open Save As
win = app.window(title_re=appTitle)
win.wait("enabled", timeout=60)
win.type_keys('%fa')    #Sends keys, but brings window to foreground

Using type_keys('%fa', set_foreground=False) will send the command to the active window. So, I am using VsCode as my text editor and 'Alt+f+a' gets sent there instead of the target application.

I have tried using send_keystrokes() instead of type_keys(), but this does not complete the command. It does send 'Alt+f' in the background but is not sending the 'a'. I have tried calling 'Alt+f' then 'Alt+a' immediately after (and with a time delay) but sending another 'Alt' just closes the opened file menu.

During my search I have seen PostMessage() from win32gui but have not been able to get that working.


Solution

  • You may try win.send_keystrokes("{VK_MENU DOWN}fa{VK_MENU UP}") to hold Alt for 2 symbols and then release it.