4

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.

SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
Chris Stone
  • 129
  • 3
  • 15

1 Answers1

7

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.

patthoyts
  • 32,320
  • 3
  • 62
  • 93
  • This worked for passing a PID from a window title, but it still never worked for my purpose, I will now take a look at UI Automation as you suggested... I am marking your answer as correct, thanks for your help in this. – Chris Stone Jan 22 '15 at 13:49