111,079
社区成员




static void Main(string[] args)
{
ManagementScope scope = new System.Management.ManagementScope(@"\\.\root\CIMV2");
WqlEventQuery query = new WqlEventQuery(
"__InstanceDeletionEvent",
new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
watcher.EventArrived += (s, e) => {
Console.WriteLine("Process {0} has been closed.",
((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value).Properties["Handle"].Value);
};
watcher.Start();
Console.ReadKey();
}
输出的就是退出进程的pid,Handle换成Name就是进程名称,ExecutablePath是映像路径,CommandLine是命令行,后两个有可能获取不到(例如win7下非管理员权限时的某些系统进程)。用PID匹配最精确。
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);//恢复窗口 1是 SW_SHOWNORMAL