[python-win32] Creating a process and getting a handle

Mike Driscoll mdriscoll at co.marshall.ia.us
Wed Jan 23 16:33:27 CET 2008


Hi Tim G., 

<snipped for brevity>

> > I can get the handle by doing this:
> > 
> > hwnd = win32gui.FindWindow('IEFrame',None)
> > 
> > But if there's multiple Explorer windows open, I may not get the 
> > window I want. That's why I would like to create my own so 
> I can have 
> > what amounts to an "exclusive" handle to it. Any hints 
> would be appreciated.
> 
> I thought I'd posted a How-Do-I? on this one, but obviously 
> not. At any rate, here's the code I intended to post up. Hope 
> it helps as a starting point:
> 
> <code>
> import subprocess
> import time
> 
> import win32con
> import win32gui
> import win32process
> 
> 
> 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)
>    return hwnds
> 
> if __name__ == '__main__':
>    notepad = subprocess.Popen ([r"notepad.exe"])
>    #
>    # sleep to give the window time to appear
>    #
>    time.sleep (2.0)
> 
>    for hwnd in get_hwnds_for_pid (notepad.pid):
>      print hwnd, "=>", win32gui.GetWindowText (hwnd)
>      win32gui.SendMessage (hwnd, win32con.WM_CLOSE, 0, 0)
> 
> </code>
> 
> TJG
> 

I think this will work. It's a little bit quicker than the method Alec
mentioned (and which I use in another part of my app) and it's definitely
a little less confusing. I just tested it by opening a couple other
instances of Notepad before running it and your script kills only the
Notepad process that it opens, as expected. Very cool.

Thanks for helping me once again.

Mike



More information about the python-win32 mailing list