Jean-philippe Emond
Jean-philippe Emond

Reputation: 1614

Python: Handle mspaint.exe Window returning 0

I'm trying to get handle on the mspaint.exe in python 3.5 but it doesn't works.

Here its the process I do and what I'm not able to do:

what I can't do:

it's my current code

Get handle function:

 # trying to get handle with title parameter
 def get_window_hwnd(title):
    hwnd = False
    list = enum_window_titles();
    for a in list:
        if title.lower() in a.lower() :
            print(a.lower()) # untitled - paint
            hwnd = win32gui.FindWindow(None, title)
            print(hwnd) # return 0
            return hwnd
    return hwnd

list windows function:

#list all windows list
def enum_window_titles():
    def callback(handle, data):
        titles.append(win32gui.GetWindowText(handle))

    titles = []
    win32gui.EnumWindows(callback, None)
    return titles

part of process:

# core
hwnd = -1
hwnd = get_window_hwnd("paint") # get handle window
print(hwnd) # 0

if(hwnd != -1 or hwnd != False): # enter here
    a = win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 0, win32api.MAKELONG(200, 200));
    b = win32api.PostMessage(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON,0);
    c = win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 0, win32api.MAKELONG(400, 400));
    d = win32api.PostMessage(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON,0);
    print(a);  #
    print(b);
    print(c);
    print(d);

The full print result:

untitled - paint
0
0
# here is the Post Message and Send Message
0
None
0
None

any Idea why I can't get handle on my mspaint?

And any Idea to know if the handle works like after PostMessage and SendMessage?

Thank you

Upvotes: 0

Views: 920

Answers (1)

David Heffernan
David Heffernan

Reputation: 612993

The window's name is "Untitled - Paint" but you are passing "paint" to FindWindow. You do need to pass the correct window name if you are going to call FindWindow. Call it like this:

win32gui.FindWindow(None, a)

However, there's no point in calling FindWindow. When you call EnumWindows, your callback receives the window handle. Remember that window handle as well as the name. That way once you find the matching name, you'll have the handle already to go. Something like this:

import win32gui

def get_window_hwnd(title):
    for wnd in enum_windows():
        if title.lower() in win32gui.GetWindowText(wnd).lower():
            return wnd
    return 0

def enum_windows():
    def callback(wnd, data):
        windows.append(wnd)

    windows = []
    win32gui.EnumWindows(callback, None)
    return windows

hwnd = get_window_hwnd("paint")
print(hwnd)

Upvotes: 1

Related Questions