Wen: http://www.codeproject.com/Useritems/wmi.asp The first translation, just want to bring a head, the translation is not good, I hope you don't joke, I believe everyone has heard of WMI. Many of the domestic websites have also introduced one here is one of CodeProject. I feel very comprehensive to translate here. I hope everyone comment, discuss the experience of writing code, Ok, translated .... .. First introduce the relevant knowledge: What is the WMI WINDOWS Management Code (Windows Management Instrument), its main features include some of the information and services to the local host, you can manage your computer remotely (of course you must have enough privileges) That is to say, I can start, shut down, closing the process, creating a process, etc.! I have a preliminary understanding of my door to start some initial work: In this WMI program, I will implement four basic functions: 1.Explorer Similar to Windows resource manager 2.systeminfo View your hardware information and OS information 3.Services Currently working information 4.Processes currently executed process (here you can manage remote and local OS), we want to start implementation Access our OS, but before this, we must introduce the system.management this namespace Let us know the status event of the control We must guarantee that it is real-time, so you must include UpdateStatus (String e) This event (this is A custom) here is mainly to refresh the status bar when you click on each control, allow the user to know what the program is doing! Code: // Control code // status event agent PUBLIC DELEGATE VOID STATUS (String E); Public Event Status UpdateStatus; // Update the status bar UpdateStatus ("Hello World."); // Here is the code // write specific event code private void refreshstatusbar (String STATUS BAR) {// update status bar Statusbarstatus.text = stringstatus;} The following is the specific code: Explorer Control first introduces the WIN32_LogicalDisk class of WMI (refer to Platform SDK: Windo ws Management Instrumentation), through which we can look to a local drive some of the details, we also need to use two classes of ManagementObjectSearcher System.Management and ManagementOjbectCollection Their main function is to ManagementOjbectCollection ManagementObjectSearcher query object to the collection (The driver information you can acquire here includes the name, type, description information, etc. of the drive). ); (reference Platform SDK: Windows Management Instrumentation) the following code: // get drive collection ManagementObjectSearcher query = new ManagementObjectSearcher ( "SELECT * From Win32_LogicalDisk"); ManagementObjectCollection queryCollection = query.Get ();
// loop throught each object to get drive information foreach (ManagementObject mo in queryCollection) {switch {case Removable (int.Parse (mo [ "DriveType"] ToString ()).): // removable drives imageIndex = 5; selectIndex = 5; Break; Case Localdisk: // local drives ImageIndex = 6; selectindex = 6; Break; case cd: // CD ROM DRIVES imageIndex = 7; selectIndex = 7; Break; Case Network: // network drives imageIndex = 8; SelectIndIndex = 8; Break; default: // defalut to folder imageindex = 2; selectindex = 3; Break;} // Get Drive Name Console.writeline ("Drive:" MO ["name"]. TOSTRING ()); } Systeminfo Control This control is primarily used to view OS and hardware information of local or remote hosts. You need to use two other objects CONNECTIONOPTIONOS and ManagementScope. ConnectionOptions are mainly setting WMI connection information, such as user names and passwords, here we mainly used Its two attributes UserName and Password; ManagementScope objects indicate WMI specification, access to server and namespaces, and use the settings in ConnectionOptions, see the following code: // connect to the Remote Computer ConnectionOptions co = New ConnectionOptions (); Co. HERNAME = TextUserId.Text; Co. Password = textPassword.text; // Point to Machine System.ma Nagement.managementscope ms = new system.management.managementscope (" stringhostname " // root // CIMv2 ", CO); Now we have to get the information we want, but we have to get those we want. What should I use? If we have to use the ObjectQuery object, through it we can get the query information we want. Place the ObjectQuery object and the ManagementScope object in the ManagementObjectSearcher object, you can set our specifications and we set up The query gets the results we want, and of course you must also drop the get () method of ManagementObjiectSearcher, which returns a collection of managementObject objects, and then access to each of our information by combining operations. The code is as follows: / / Query system for Operating System information oq = new System.Management.ObjectQuery ( "SELECT * FROM Win32_OperatingSystem"); query = new ManagementObjectSearcher (ms, oq); queryCollection = query.Get ();
foreach (ManagementObject mo in queryCollection) {// create child node for operating system createChildNode (nodeCollection, "Operating System:" mo [ "Caption"]); createChildNode (nodeCollection, "Version:" mo [ "Version"]) ; createChildNode (nodeCollection, "Manufacturer:" mo [ "Manufacturer"]); createChildNode (nodeCollection, "Computer Name:" mo [ "csname"]); createChildNode (nodeCollection, "Windows Directory:" mo [ "WindowsDirectory "]); Code as follows: ManagementObjectSearcher query = new ManagementObjectSearcher ( "SELECT * From Win32_OperatingSystem"); ManagementObjectCollection queryCollection = query.Get (); described here is a method of OS information, such as additional view Bios, Memory.Network Connection information only You need to change the query word! (Refer to Platform SDK: Windows Management Instrumentation) Service Control Control: This control is used to use a new query word "SELECT * WIN32_SERVICE", you can get the system by it. There are those services that exist. In order to facilitate start and termination of a service, we can Create a pop-up menu in ListView, when using the Item in ListView with the mouse, you can use it to start or terminate a service. You can specify the service you want "SELECT * from Win32_Service Where name = ' ServiceName '", this time we want to call ManagementObject.invokeMethod () to specify whether to terminate or start a service. InvokeMethod () is an object of a ManagementBaseObject. It is used as a base class for more specific management object classes. I manage asynchronous operations and process asynchronous management information and events through a ManagementoperationObserver object. You can determine whether the value is successful by the value of COMPLETONHANDLEROBJ.RETURNOBJECT (attribute to a custom class). The code is as follows: ///
/// List view mouse down event to built context menu dynamically /// /// /// private void listViewServices_MouseDown (object sender, System.Windows.Forms.MouseEventArgs e) {System.Windows.Forms.ListView listViewObject = (System .Windows.Forms.ListView) sender; ContextMenu mnuContextMenu = new ContextMenu (); menuItem menuItem = new menuItem (); ManagementObjectCollection queryCollection; // check if right button if (e.Button == System.Windows.Forms.MouseButtons.Right ) {// get service name ServiceName = listViewObject.GetItemAt (eX, eY) .Text; // set list view item ServiceItem = listViewObject.GetItemAt (eX, eY); // create popup menu listViewObject.ContextMenu = mnuContextMenu; try { // get specific service object queryCollection = getServiceCollection ( "SELECT * FROM Win32_Service Where Name = '" ServiceName "'"); foreach (ManagementObject mo in queryCollection) {// create menu depending on service state if (mo [ "Started "] .Equals (true)) {meNuitem.text =" stop "; // set action property serv iceAction = "StopService";} else {menuItem.Text = "Start"; ServiceAction = "StartService";} mnuContextMenu.MenuItems.Add (menuItem); // Add functionality to the menu items using the Click event menuItem.Click . = New System.EventHandler (this.Menuitem_Click);}} catch (Exception E1) {MessageBox.show ("Error:" E1);}}} ////
/// List view context menu click event to invoke start / stop service /// /// /// 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;! ". Terminate process timed out" while (completionHandlerObj.IsComplete) {if (intCount> 10) {MessageBox.Show ( , "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 (serviceAdition == "startservice) stringAction =" start "; else stringAction =" stop ";
Messagebox.show ("failed to" stringAction "service" service ");} // clean-up objects service} // clean-up objects service =" "; serviceAction =" "; serviceItem = NULL // status updatestatus ("ready"); this.Update ();} // ------------------------------ ---- // Completion Handler // ------------------------------------------------------------------------- Management; namespace completionHandler {////// MyHandler class handle notification when InvokeMethod call is complete /// public class MyHandler {private bool isComplete = false; private ManagementBaseObject returnObject; ///
/// Trigger Done Event when InvokeMethod Is Complete /// Public Void Done (Object Rene "e) {iScomplete = true; returnobject = E.NEWOBJECT;} ///
/// Get Property Iscomplete /// Public Bool Iscomplete {Get {Return ISComplete;}} ///
/// Property allows accessing the result object in the main function /// public ManagementBaseObject ReturnObject {get {return returnObject;}}}} ProcessesControl Control Application: This control system mainly used for displaying a running process, such as: the user process .CPU utilization, memory usage. We can use the Getowner (User, Domain) method to know who the process owner is. IUSER and DOMAIN are entrance parameters, but how do we get this entrance parameter from InvokeMethod? Here we need to implement invokeMethod. Discuss two cases 1. We don't need asynchronous operation, we only need a string [] array to complete 2. When we need asynchronous operation, we only need a completionHandlerobj.ReturnObject property to collect Object. The code is as follows: // ------------------------------------------- ------ // Get Process Owner INFO without the observer object // -------------------------------- ------------------ // Createan Array Containing All arguments for the method string [] methodargs = {","}; // get process Owner Info Mo.invokeMethod ("Getowner", methodargs; // methodargs [0] - Contain Process User //Methodargs [1] = Contain Process Domain // ------------------------------------------------------------------------------------------------------------ --------------------------- // GetProcess Owner Info with the observer object // ------------ ----------------------------------- Mo.invokemeth OD (Observer, "Getowner", NULL; while (! companyLetrandlerobj.iscomplete) {system.threading.thread.sleep (500);} if (completionageLerobj.ReturnObject ["ReturnValue"]. Tostring () == "0" ) structProcess.stringUserName = completionHandlerObj.ReturnObject.Properties [ "User"] value.ToString (); else structProcess.stringUserName = ""; discuss how to end the following processes: the end of a specified process is very similar to the above-mentioned start-up or Terminate a service. First of now, you will use the ManagementObject object to specify the process you want, then call InvokeMethod (Observer, "Terminate", null) to terminate a process. The code is as follows: // 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 ManagementObject for process 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 (! ") {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 Pro CESS ");}} Create a process: Create a new process We need to call the ManagementClass class's InvokeMethod method to complete our CanagementClassClassClass = New ManagementClass (MS, PATH, NULL); this statement is implemented. MS. MS. Is an instance of a ManagementScope class; Path is an instance of ManagementPath. ManagementScope To set the range of management. ManagementPath is used to provide a package for analyzing and generating a path to WMI objects. ("Win32_Process"
) Prior to this, we also need to call ManagementClass.InvokeMethod (observer, methodName, inParameters) we can pass to a four parameter .inParameters is actually a Create Method in Class Win32_Process (Reference Platform SDK through an array of objects:. Windows Management Instrumentation ) uint32 Create (string CommandLine, string CurrentDirectory, Win32_ProcessStartup ProcessStartupInformation, uint32 * ProcessId); Parameters CommandLine - [in] Command line to execute The system adds a null character to the command line, trimming the string if necessary, to indicate which file. was actually used CurrentDirectory -.... [in] Current drive and directory for the child process The string requires that the current directory resolves to a known path A user can specify an absolute path or a path relative to the current working directory If this parameter is NULL, the new process will have the same path as the calling process. This option is provided primarily for shells that must start an application and specify the application's initial drive and working directory. Process StartupInformation - [in] The startup configuration of a Windows process For more information see Win32_ProcessStartup ProcessId -.. [Out] Global process identifier that can be used to identify a process The value is valid from the time the process is created until the time. the process is terminated, for example, the code: // Create an array containing all arguments for the method object [] methodArgs = {stringCommandLine, null, null, 0}; // Execute the method processClass.InvokeMethod (observer, "Create", methodArgs) The following code is used to create and insert a new process. We can write a CREATEPROCESS function to pass a parameter stringcommandline to pass a process you want to create. If you can write createProcess ("Calc.exe"), then you You can create a calculator process. Here is an example. The code is as follows; ///
/// Invoke method 'Create' on local or remote machine /// /// 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;