2

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

1 Answer 1

5

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I was able to get the output of your function to plug in with win32gui.GetWindowDC after some minor tweaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.