技术开发 频道

使用C#制做进程监视器


【IT168技术文档】

/// <summary> /// 使用Wmi获取指定进程的创建者等信息 /// </summary> /// <param name="pID">进程ID</param> private void FillDetailUseWmi(int pID) { ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ProcessID=" + pID); ManagementObjectCollection moc = searcher.Get(); ManagementOperationObserver observer = new ManagementOperationObserver(); HandleObjectReady hor = new HandleObjectReady(); //监测异步方法是否已成功返回 observer.ObjectReady += new ObjectReadyEventHandler(hor.Done); foreach (ManagementObject mo in moc) { //异步调用该对象的GetOwner方法,获取进程创建者 mo.InvokeMethod(observer, "GetOwner", null); //等待异步调用返回 while (!hor.Complete) { System.Threading.Thread.Sleep(500); } string user = ""; //判断获取用户名的操作是否成功 if (hor.Obj["returnValue"].ToString() == "0") { user = hor.Obj.Properties["User"].Value.ToString(); } //判断字典中是否已移除该项 if (!this.mDict.ContainsKey(pID)) { return; } if (mo["ParentProcessID"] != null && this.mDict.ContainsKey(Convert.ToInt32(mo["ParentProcessID"]))) { //根据父进程ID获取父进程名称 this.mDict[pID].ParentProce = this.mDict[Convert.ToInt32(mo["ParentProcessID"])].ProceName; } this.mDict[pID].Creator = user; //触发刷新进程详细信息事件 if (this.HandleDetailList != null) { this.HandleDetailList(this.mDict[pID]); } } //释放资源 searcher.Dispose(); searcher = null; moc.Dispose(); moc = null; observer = null; hor = null; } /// <summary> /// 该类用于监测Wmi异步调用方法是否已经返回 /// </summary> public class HandleObjectReady { private bool complete = false; private ManagementBaseObject obj; public void Done(object sender, ObjectReadyEventArgs e) { complete = true; obj = e.NewObject; } public bool Complete { get { return complete; } } public ManagementBaseObject Obj { get { return obj; } } }
0
相关文章