/// <summary> /// List view context menu click event to invoke terminate process /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void menuItemTerminate_Click(object sender, System.EventArgs e) { ManagementObjectCollection queryCollection; ListViewItem lvItem; //Set up a handler for the asynchronous callback ManagementOperationObserver observer = new ManagementOperationObserver(); completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done); queryCollection = getProcessCollection("Select * from Win32_Process Where ProcessID = '" + ProcessID + "'"); //Status updateStatus("Invoking terminate process"); foreach ( ManagementObject mo in queryCollection) { //start or stop service mo.InvokeMethod(observer, "Terminate", null); } //wait until invoke method is complete or 5 sec timeout int intCount = 0; while (!completionHandlerObj.IsComplete) { if (intCount == 10) { MessageBox.Show("Terminate process timed out.", "Terminate Process Status"); break; } //wait 1/2 sec. System.Threading.Thread.Sleep(500); //increment counter intCount++; } if (intCount != 10) { //InvokeMethod did not time out if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0") { lvItem = ProcessItem; lvItem.Remove(); } else { MessageBox.Show("Error terminating process.", "Terminate Process"); } } //clean-up objects ProcessID = ""; ProcessItem = null; //Status updateStatus("Ready"); this.Update(); }
/// <summary> /// Invoke method 'Create' on local or remote machine /// </summary> /// <param name="stringCommandLine"></param> private void CreateProcess(string stringCommandLine) { //Set up a handler for the asynchronous callback ManagementOperationObserver observer = new ManagementOperationObserver(); completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done); string stringMachineName = ""; //Connect to the remote computer ConnectionOptions co = new ConnectionOptions(); if (radioMachine.Checked == true) { stringMachineName = "localhost"; } else { stringMachineName = textIP.Text; } if (stringMachineName.Trim().Length == 0) { MessageBox.Show("Must enter machine IP address or name."); return; } //get user and password if (textUserID.Text.Trim().Length > 0) { co.Username = textUserID.Text; co.Password = textPassword.Text; } //Point to machine System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\" + stringMachineName + "\\root\\cimv2", co); //get process path ManagementPath path = new ManagementPath( "Win32_Process"); //Get the object on which the method will be invoked ManagementClass processClass = new ManagementClass(ms,path,null); //Status updateStatus("Create process " + stringCommandLine + "."); //Create an array containing all arguments for the method object[] methodArgs = {stringCommandLine, null, null, 0}; //Execute the method processClass.InvokeMethod (observer, "Create", methodArgs); //wait until invoke method is complete or 5 sec timeout int intCount = 0; while (!completionHandlerObj.IsComplete) { if (intCount > 10) { MessageBox.Show("Create process timed out.", "Terminate Process Status"); break; } //wait 1/2 sec. System.Threading.Thread.Sleep(500); //increment counter intCount++; } if (intCount != 10) { //InvokeMethod did not time out //check for error if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0") { //refresh process list this.Refresh(); } else { MessageBox.Show("Error creating new process.", "Create New Process"); } } //Status updateStatus("Ready"); this.Update(); }
/// <summary> /// Get processes and populate list view /// </summary> private void getProcess() { ManagementObjectCollection queryCollection; ManagementObjectCollection queryCollection1; ProcessesDictionary.ProcessesDictionary processesDictionary = new ProcessesDictionary.ProcessesDictionary(); ProcessesDictionary.ProcessesInfo processInfo; ProcessesDictionary.structProcessInfo structProcess; ProcessesPerformanceDictionary.Dictionary dictionaryPerformances = new ProcessesPerformanceDictionary.Dictionary(); ProcessesPerformanceDictionary.structPerformance structProcessPerf; ProcessesPerformanceDictionary.ProcessPerf processPerformance; //Set up a handler for the asynchronous callback ManagementOperationObserver observer = new ManagementOperationObserver(); completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done); string[] lvData = new string[5]; //Status updateStatus("Getting Services Information"); //prevent listview update listViewProcesses.BeginUpdate(); try { //get system processes collection queryCollection = getProcessCollection("SELECT * FROM Win32_Process"); //create dictionary for processes foreach ( ManagementObject mo in queryCollection) { processInfo = new ProcessesDictionary.ProcessesInfo(); structProcess = new ProcessesDictionary.structProcessInfo(); structProcess.stringName = mo["Name"].ToString(); structProcess.stringProcessID = mo["ProcessID"].ToString(); structProcess.stringParentProcessID = mo["ParentProcessID"].ToString(); //Status updateStatus("Getting " + structProcess.stringName + " process info..."); //Get process owner info mo.InvokeMethod(observer,"GetOwner", null); //wait until call is complete while (!completionHandlerObj.IsComplete) { System.Threading.Thread.Sleep(500); } //check if the call was successful if (completionHandlerObj.ReturnObject["returnValue"].ToString() == "0") //get process user name structProcess.stringUserName = completionHandlerObj.ReturnObject.Properties["User"].Value.ToString(); else //failed structProcess.stringUserName = ""; processInfo.Value = structProcess; processesDictionary.Add(mo["ProcessID"].ToString(), processInfo); } //get operating system string stringOS = ""; int intWinXP = 0; queryCollection = getProcessCollection("SELECT * FROM Win32_OperatingSystem"); foreach(ManagementObject mo in queryCollection) { //look for Windows 2000 Operating system stringOS = mo["Caption"].ToString(); intWinXP = stringOS.LastIndexOf("XP"); } if (intWinXP >= 0) { //get process CPU and memory usage for XP machine //(Note: have problem calling this on 2000 and NT machine.) queryCollection1 = getProcessCollection("SELECT * FROM Win32_PerfFormattedData_PerfProc_Process"); } else { //get process CPU and memory usage for 2000 and NT machine queryCollection1 = getProcessCollection("SELECT * FROM Win32_PerfRawData_PerfProc_Process"); } foreach ( ManagementObject mo1 in queryCollection1) { //get process CPU and memory usage processPerformance = new ProcessesPerformanceDictionary.ProcessPerf(); structProcessPerf = new ProcessesPerformanceDictionary.structPerformance(); structProcessPerf.stringPercentProcessorTime = mo1.Properties["PercentProcessorTime"].Value.ToString(); structProcessPerf.stringVirtualBytes = mo1["VirtualBytes"].ToString(); processPerformance.Value = structProcessPerf; //add to dictionary dictionaryPerformances.Add(mo1["IDProcess"].ToString(), processPerformance); //cleanup processPerformance = null; } //populate listview foreach (string stringProcessID in processesDictionary) { //currentProcessInfo = processesDictionary[stringProcessID].Value; structProcess = processesDictionary[stringProcessID].Value; //create child node for operating system lvData[0] = structProcess.stringName.ToString(); //get process id lvData[4] = structProcess.stringProcessID.ToString(); //get parent process lvData[1] = structProcess.stringUserName.ToString(); try { //get process % processor time lvData[2] = dictionaryPerformances[structProcess.stringProcessID.ToString()].Value.stringPercentProcessorTime.ToString(); //get memory usage lvData[3] = dictionaryPerformances[structProcess.stringProcessID.ToString()].Value.stringVirtualBytes.ToString(); } catch(NullReferenceException) { //can't find process performance data lvData[2] = "0"; lvData[3] = "0"; } //create list item ListViewItem lvItem = new ListViewItem(lvData,0); listViewProcesses.Items.Add(lvItem); } } catch (Exception e) { MessageBox.Show("Error: " + e); } //do some cleanup processesDictionary.Clear(); processesDictionary = null; dictionaryPerformances.Clear(); dictionaryPerformances = null; //update listview listViewProcesses.EndUpdate(); //Status updateStatus("Ready"); this.Update(); }
/// <summary> /// List view context menu click event to invoke start/stop service /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void menuItem_Click(object sender, System.EventArgs e) { ManagementObjectCollection queryCollection; ListViewItem lvItem; //Set up a handler for the asynchronous callback ManagementOperationObserver observer = new ManagementOperationObserver(); completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler(); observer.ObjectReady += new ObjectReadyEventHandler(completionHandlerObj.Done); //get specific service object queryCollection = getServiceCollection("Select * from Win32_Service Where Name = '" + ServiceName + "'"); //Status updateStatus("Starting/Stopping service..."); foreach ( ManagementObject mo in queryCollection) { //start or stop service mo.InvokeMethod(observer, ServiceAction, null); } //wait until invoke method is complete or 5 sec timeout int intCount = 0; while (!completionHandlerObj.IsComplete) { if (intCount > 10) { MessageBox.Show("Terminate process timed out.", "Terminate Process Status"); break; } //wait 1/2 sec. System.Threading.Thread.Sleep(500); //increment counter intCount++; } //see if call was successful. if (completionHandlerObj.ReturnObject.Properties["returnValue"].Value.ToString() == "0") { //succeeded lvItem = ServiceItem; if (ServiceAction == "StartService") lvItem.SubItems[2].Text = "Started"; else lvItem.SubItems[2].Text = "Stop"; } else { //error message string stringAction; if (ServiceAction == "StartService") stringAction = "start"; else stringAction = "stop"; MessageBox.Show("Failed to " + stringAction + " service " + ServiceName + ".", "Start/Stop Service Failure"); } //clean-up objects ServiceName = ""; ServiceAction = ""; ServiceItem = null; //Status updateStatus("Ready"); this.Update(); }