My purpose want to catch TASKKILL event in Command Prompt, and use this event.
Maybe, I think need to use kernel32.dll
but I can't find a handler for this.
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
Update
Follow ways @Ben Voigt suggest:
_Using WMI:
Step 1: Run the command mgmtclassgen Win32_Process /n root\\cimv2 /o WMI.Win32
to generate the class Process
. And then renaming the class Process
to Win32_Process
.
http://notepad.cc/share/3SQfeJgEQR
Step 2: Create a class with name ProcessWatcher
http://notepad.cc/share/UIR1Tw5twy
Step 3: Using this class with while
loop for waiting my application status. This is easy way but not my choice.
http://notepad.cc/share/JXLGogGbai
_Using Window Hook:
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
ushort hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle,
uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
But TerminateProcess
and DuplicateHandle
, I can't find a handler for this.
From some other process, which we shall call the watchdog, you must get a handle to the process you will monitor for termination (the target process). You can have a handle created using DuplicateHandle
and communicated via an IPC mechanism. If you know the PID of the target process, you can use OpenProcess
or System.Diagnostics.Process.GetProcessById
. If the target process is spawned by the watchdog, you get a handle from CreateProcess
or System.Diagnostics.Process.Start
. Or you can enumerate running processes, for example using System.Diagnostics.Process.GetProcessesByName
.
In any case, once you have a handle to the process, you can pass it to one of the wait functions such as WaitForSingleObject
, WaitForMultipleObjects
, or MsgWaitForMultipleObjectsEx
. When the process ceases running, for example because TASKKILL terminated it, the process handle becomes signaled and the wait will complete.
If you use the .NET Process
class and its WaitForExit
method, be aware that unlike the Win32 wait functions, there is no multi-handle version; you'll need to dedicate an entire thread.
A possibly easier way is to use WMI and subscribe to process events. I tend not to use WMI myself, but it could be useful if you don't have a parent/child relationship between watchdog and target, making the handle otherwise difficult to get. You can read about it on this blog:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.