Search code examples
pythonsubprocesspywin32

Set Active / Foreground window from PID


I am trying to set a program (known PID) to the top / active /foreground (not sure which is most appropriate).

The PID is set to the windows process PID

    handle = win32api.OpenProcess( win32con.PROCESS_ALL_ACCESS,
                        False, pid)
    win32gui.SetForegroundWindow(handle)
    win32gui.SetActiveWindow(handle)

I either get:

    pywintypes.error: (1400, 'SetForegroundWindow', 'Invalid window Handle.')

    pywintypes.error: (1400, 'SetActiveWindow', 'Invalid window handle.')

I realize it is a problem in the handler but im not sure how I am supposed to properly get the working handle.


Solution

  • This job can be done by pywinauto:

    from pywinauto import Application
    app = Application().connect(process=<pid>)
    app.top_window().set_focus()
    

    But it may not work for minimized app.