Kill process based on window name (win32)

drodrig drodrig at magicbrain.com
Sat Aug 12 15:17:38 EDT 2006


Thank you Roger. Your advice did the trick. For anyone interested, the
basic code to terminate a process (politely) would be something like
this (hwnd is retrieved using win32gui.EnumerateWindows):

# Get the window's process id's
t, p = win32process.GetWindowThreadProcessId(hwnd)
# Ask window nicely to close
win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)
# Allow some time for app to close
time.sleep(10)
# If app didn't close, force close
try:
    handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, p)
    if handle:
        win32api.TerminateProcess(handle,0)
	win32api.CloseHandle(handle)
except:
    pass:

Roger Upole wrote:
> drodrig wrote:
> > Hi.
> >
> > I am trying to close/kill all processes that show visible windows on
> > Windows XP. So far I've created a script that uses win32gui.EnumWindows
> > to iterate through all windows, check for which windows are visible,
> > then send a WM_CLOSE message to the window to request that it closes.
> > Of course, not all apps want to close nicely. At this point I need to
> > use something like TerminateProcess to kill the app, but how do I find
> > the process id (hopefully based on the window id).
> >
> > Thanks for any help.
> >
>
> win32process.GetWindowThreadProcessId should do the trick.
> 
>        Roger




More information about the Python-list mailing list