-2

I used win32process.CreateProcess function created a process:

handle = win32process.CreateProcess('LabMax.exe', '',
                                None, None, 0, win32process.CREATE_NO_WINDOW,
                                None, None, win32process.STARTUPINFO())
print(handle)

The handle showed:

(<PyHANDLE:600>, <PyHANDLE:860>, 11696, 10648)

Then I tried to get windows text by the first PyHANDLE:

title = win32gui.GetWindowText(handle[0])
print('Title:',title)

But it showed NOTHING:

Title:''

I have tried some other functions which required PyHANDLE object, but all of them didn't work.

why?

  • 2
    `CreateProcess` returns a process handle and a thread handle (and a process ID and a thread ID). Neither of those are windows. In fact, you specifically requested `CREATE_NO_WINDOW`. Why are you expecting a window handle at all? – Tim Roberts Nov 23 '21 at 04:15

1 Answers1

0

Thanks for Tim, and I got the reason, that the handle from CreateProcess is not the windows handle. Finally, I used PID to find it:

import win32process
import win32gui
import win32event

handle = win32process.CreateProcess('C:\\Windows\\notepad.exe', '',
                                    None, None, 0, win32process.CREATE_NO_WINDOW,
                                    None, None, win32process.STARTUPINFO())
print(handle)
while True:
    if win32event.WaitForSingleObject(handle[0], 100):
        break

def get_hwnds_for_pid(pid):
    def callback(hwnd, hwnds):
        if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
            _, found_pid = win32process.GetWindowThreadProcessId(hwnd)
            if found_pid == pid:
                hwnds.append(hwnd)
                return True
    hwnds = []
    win32gui.EnumWindows(callback, hwnds)
    hwndy = 0
    if hwnds:
        hwndy = hwnds[0]
    return hwndy

hwndy = get_hwnds_for_pid(handle[2])
print(hwndy)
title = win32gui.GetWindowText(hwndy)
print('Title:',title)