Skip to content Skip to sidebar Skip to footer

Get Window Handler From Started Process

I see there's win32process.GetWindowThreadProcess() that gets a window handler and returns it's process id. Is there a way to do the opposite: get the window handler of a running p

Solution 1:

I dont think that Windows API provides a method for this , but you could iterate over all open windows , and find the one that belongs to you .

I have modified your program so it looks like this :

import win32process
import win32process as process
import win32gui
import sys

PORTABLE_APPLICATION_LOCATION = "C:\\Windows\\system32\\notepad.exe"
processHandler = -1defcallback(hwnd, procid):
    if procid in  win32process.GetWindowThreadProcessId(hwnd):
        win32gui.SetForegroundWindow(hwnd)

defshow_window_by_process(procid):
    win32gui.EnumWindows(callback, procid)


defrunProgram():
    global processHandler
    #don't run a process more than onceif (isLiveProcess(processHandler)):
        #Bring focus back to running window!
        show_window_by_process(processHandler)
        return;
    try:
        startObj = process.STARTUPINFO()
        myProcessTuple = process.CreateProcess(PORTABLE_APPLICATION_LOCATION,None,None,None,8,8,None,None,startObj)
        processHandler = myProcessTuple[2]
    except:
        print(sys.exc_info[0])

defisLiveProcess(processHandler): #Process handler is dwProcessId
    processList = process.EnumProcesses()
    for aProcess in processList:
        if (aProcess == processHandler):
            returnTruereturnFalse

 runProgram()

Post a Comment for "Get Window Handler From Started Process"