Search code examples
pythonpywin32win32gui

How to get handle for a specific application window in Python using pywin32?


I am attempting to modify some Python code that takes a screenshot of a particular application window in Windows 10. I am trying to use the win32ui / win32gui modules from the pywin32 package for this purpose. Here is the broken code:

def getWindow():
    name = "Windows PowerShell"
    window = win32ui.FindWindow(None, name)
    windowDC = win32gui.GetWindowDC(window)

The last line causes the error. Here is the relevant portion of the console output:

  File ".\fake_file_name.py", line 9, in getWindow
    windowDC = win32gui.GetWindowDC(window)
TypeError: The object is not a PyHANDLE object

I'm not very familiar with Python's type system or error messages, but this error makes it seem like GetWindowDC was expecting an argument with type PyHANDLE. The documentation I could find for win32gui.FindWindow makes it seem like a PyHANDLE is indeed the output type.

On the other hand, these very similar lines of code came from a function that does work:

    hwin = win32gui.GetDesktopWindow()
    hwindc = win32gui.GetWindowDC(hwin)

Here is the doc page for win32gui.GetDesktopWindow. If the previously shown error message didn't specifically mention PyHANDLE, I would just assume that FindWindow and GetDesktopWindow return different and incompatible types.

Can someone help me understand what this error message means and why it is appearing? I would also be interested in example code that gets a device context for a window with the name "Windows Powershell", as my broken code attempted to do.

Other info: Documentation page for win32gui.GetWindowDC


Solution

  • You can use EnumWindows(),this will search all the window,Read it in MSDN doc:

    import win32gui
    
    def getShell():
        thelist = []
        def findit(hwnd,ctx):
            if win32gui.GetWindowText(hwnd) == "Windows PowerShell": # check the title
                thelist.append(hwnd)
    
        win32gui.EnumWindows(findit,None)
        return thelist
    
    b = getShell()
    print(b) # b is the list of hwnd,contains those windows title is "Windows PowerShell"