Killing Like Task Manager

556 Views Asked by At

Inside Task Manager [Windows 8+], in the "Processes" tab it lists all the processes currently running. If we open 2 windows of MS Word, it will only appear once, however this is actually a group and can be expanded to be able to see and end both tasks separately.

This is great, however it DOES NOT carry over to the "Details" tab where WINWORD.EXE is listed but only 1 occurrence! And thus only 1 PID! Sharing a PID is an issue because an attempt to close it results in the entire thingbeing closed.

I want to only kill a specific word window, not ALL word windows which has been happening when I try to kill windows programatically (currently i'm using taskkill through an import os in python, any other way to do it without additional modules would be alright as well).

Right now when I run taskkill.... "WordDoc.docx" it kills every open word document which is extremely annoying and potentially data losing. Is there a way to be able to kill "proccesses" like how it is done in task manager?

Thank you

PS I am not using /T so that is not the issue

1

There are 1 best solutions below

2
On

When closing a single window of a process on the Process tab, Task Manager does not kill the process the window belongs to, but just sends a WM_CLOSE message to that window. You will notice that the Word window is not "killed" as you will still get a prompt to save and unsaved changes in your Word document.

You can do the same as Task Manager using the following code, which enumerates all top-level windows, and then sends WM_CLOSE if the window title matches a desired value:

import win32gui

def enumHandler(hwnd, lParam):
    if win32gui.IsWindowVisible(hwnd):
        if 'My Word Document' in win32gui.GetWindowText(hwnd):
            win32gui.PostMessage(hwnd, win32con.WM_CLOSE, 0, 0)

win32gui.EnumWindows(enumHandler, None)