Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a PID from a window title in windows OS using Python?

I need to feed a PID from a window that I know the title of.

It's an installer program that seems to change vital credentials when the first "next" button is programmatically pressed in my code.

I think it does this because the window fades away and then fades back in again but when I click the back button and click next again it doesn't do it again.

The first "next" button, the first time I click it, has a shield on it so I think it might have something to do with UAC.

I am sending the window a ENTER keyboard press with this code:

import win32com.client


shell = win32com.client.Dispatch("WScript.Shell")


def setwindowfocus(windowname):  # can be the window title or the windows PID

    shell.AppActivate(windowname)


def sendkeypresstowindow(windowname, key):

    setwindowfocus(windowname)
    shell.SendKeys(key)
    time.sleep(0.1)


sendkeypresstowindow(u'Some Known Window Title', '{ENTER}')
time.sleep(5)  # Wait for next window
sendkeypresstowindow(u'Some Known Window Title', '{ENTER}')
time.sleep(5)  # Wait for next window

The shell.AppActivate() can take a pid also so I was wondering how I would get that if the only information I have is the windows title.

I have tried using pywinauto and run into the same problem, besides many of the members that should not be accessible in pywinauto are and its very unintuitive as to what I need to do to use it so I would rather steer clear of it until the code is cleaned up..

I also noticed that the handle of the window changes so If I can somehow get the handle from the window title and then the PID from the handle that would work also.

like image 677
Chris Stone Avatar asked Oct 28 '25 02:10

Chris Stone


1 Answers

The GetWindowThreadProcessId function seems to do what you want for getting a PID from a HWND. And FindWindow is the usual way to find a window using its title. So the following gets a

import win32gui,win32process
def get_window_pid(title):
    hwnd = win32gui.FindWindow(None, title)
    threadid,pid = win32process.GetWindowThreadProcessId(hwnd)
    return pid

I wonder if you should be trying to use UI Automation though if you are trying to drive the UI. I've not tried to use that via Python.

like image 99
patthoyts Avatar answered Oct 29 '25 16:10

patthoyts