// this method was based on the code from http://www.dreamincode.net/forums/showtopic67090.htm // (this version has some modifications on the original code, and was copied from reflector) public static DataTable GetRunningProcesses() { string wmiClass = "Win32_Process"; string condition = ""; string[] queryProperties = new string[] { "Name", "ProcessId", "Caption", "ExecutablePath", "CommandLine" }; SelectQuery wmiQuery = new SelectQuery(wmiClass, condition, queryProperties); ManagementScope scope = new ManagementScope(@"\\.\root\CIMV2"); ManagementObjectCollection runningProcesses = new ManagementObjectSearcher(scope, wmiQuery).Get(); DataTable queryResults = new DataTable(); queryResults.Columns.Add("Name", Type.GetType("System.String")); queryResults.Columns.Add("ProcessId", Type.GetType("System.Int32")); queryResults.Columns.Add("Caption", Type.GetType("System.String")); queryResults.Columns.Add("Path", Type.GetType("System.String")); queryResults.Columns.Add("CommandLine", Type.GetType("System.String")); foreach (ManagementObject obj in runningProcesses) { DataRow row = queryResults.NewRow(); row["Name"] = obj["Name"].ToString(); row["ProcessId"] = Convert.ToInt32(obj["ProcessId"]); if (obj["Caption"] != null) { row["Caption"] = obj["Caption"].ToString(); } if ((obj["ExecutablePath"] != null) && (obj["CommandLine"] != null)) { string rawCommandLine = obj["CommandLine"].ToString(); string executablePath = obj["ExecutablePath"].ToString(); row["Path"] = executablePath; if (rawCommandLine.StartsWith("\"" + executablePath + "\"")) { rawCommandLine = rawCommandLine.Substring(executablePath.Length + 2); } else if (rawCommandLine.StartsWith(executablePath)) { rawCommandLine = rawCommandLine.Substring(executablePath.Length); } row["CommandLine"] = rawCommandLine; } queryResults.Rows.Add(row); } return queryResults; }
public ManagementObjectSearcher(ManagementScope scope, SelectQuery wmiQuery) { obj = "ManagementObjectSearcher".ctor("System.Management", scope.obj, wmiQuery.obj); }