Original: 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 me.
I believe that everyone has heard of WMI, and many websites in China have introduced it. This is one of CodeProject. I think it is very comprehensive to translate it. I hope everyone comment, discuss the experience of writing code. , Ok has not said, translated ...
First introduce relevant knowledge: What is the WMI WINDOWS Management Code (Windows Management Instrument), its main features include some information and services to local hosts, can remotely manage computers (of course, you must have enough permissions) You can restart, shut down, close the process, create a process, etc.!
With a preliminary understanding of my gates, I started a preliminary work: In this WMI program, I will implement four basic functions: 1.Explorer Similar to the resource manager in Windows 2.SystemInfo View your hardware information and OS information 3.Services is currently working in information 4. Processes currently executed process (here you can manage remote and local OS)
Ok, we have to start an OS to access our, but we must introduce this namespace in System.Management before this.
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, let users know what the program is doing!
Code Sample: // Control code // Status event agent PUBLIC DELEGATE VOID Status (String E); public evenet status updatestatus; // updates the status bar Updatestatus ("Hello World.");
/ / Here is the code // write specific event code private void refreshstatusbar (StringStatus) {// update status bar statusbarstatus.text = stringstatus;}
Below is specific code:
Explorer Control
Here's Win32_LogicalDisk first introduce WMI class (Reference Platform SDK: Windows Management Instrumentation), through which we can see some details of the local drive, we also need to use two classes ManagementObjectSearcher and ManagementOjbectCollection System.Management of their role Mainly managementObjectSearcher will query the collection of managementojibectCollection this object (here you can get the drive information including the drive's name, type, description information, etc.) Of course, you can only view some information of the drive can be in the constructor of the managementObjectSearcher class. write ManagementObjectSearcher query = new ManagementObjectSearcher ( "SELECT * From Win32_LogicalDisk"); (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 use it two The property username and password; managementScope object indicates the WMI specification, access the path to the server and namespace, and use the settings in ConnectionOption, please see the following code: // Connect To the Remote ComputerConnectionOptions CO = New ConnectionOptions ();
Co. HERNAME = TEXTUSERID.TEXT; Co. Password = TextPassword.Text;
// Point to MachineSystem.Management.ManagementsCope MS = New System.Management.ManagementsCope (" StringHostName " // Root // CIMv2 ", CO);
Now let's get the information we want, but we have to get the information we want? If we must use the ObjectQuery object, through it we can get the query information we want. ObjectQuery object And the ManagementScope object is placed in the ManagementObjectSearcher object. You can get the results we want through us to set the results we want. Of course, you must also drop the Get () method of ManagementObjiectSearcher, which will return a managementObject object. Collection, can then access each of our information by combining operations.
The following code: // Query system for Operating System informationoq = 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"]);} If you just want to view the information of the local host, you don't have to create a ConnectionOption, ManagementScope, ObjectQuery object, you just need to call the result in the ManagementObjectCollection collection in the managementObjectCollection collection.
The code is as follows: managementObjectSearcher query = new managementObjectsearcher ("Select * from win32_operatingsystem"); managementObjectCollection queryCollection = query.get ();
Here is just the method of the OS information. Other information such as BIOS, Memory.Network Connection, etc., you only need to change the query word! (Can refer to Platform SDK: Windows Management Instrumentation)
Service Control Control: This control is used to use a new query word "Select * from win32_service", through which we can get those services in the system. In order to facilitate startup and terminating a service, we can dynamic in ListView Create a pop-up menu that can be used to start or terminate a service when using the Item in ListView with the mouse, you can specify the service you want "Select * from win32_service where name = 'serviceename", this When we want to call ManagementObject.invokeMethod () to specify whether the first parameter of the termination or starting a service. InvokeMethod () is an object of a managementbaseObject. It uses a base class for more specific management object classes. I passed a ManagementOperationObserver object. Manage asynchronous operations and processed management information and events received asynchronous. It can be judged to be successful by the value of the value of COMPLETLEROBJ.RETURNOBJECT (attribute to a custom class).
Code is as follows: ///
// 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 serviceAction = "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);}} }
///
// 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 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 =" start "; 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 service = ""; service = ""; serviceItem = null;
// status updatestatus ("ready"); this.Update ();}
/ / ---------------------------------- // Completion Handler // -------- -----------------------------------------
namespace completionHandler {///
///
///
}
ProcesseSControl control: This control is mainly used to display the running processes in the system, such as: user process. CPU utilization, memory usage. We can learn who the process of the process via the Getowner (User, Domain) method. User and Domain are entry parameters, but the problem is how we get this entry parameter from InvokeMethod? Here we need to implement invokeMethod. Discuss two cases 1. We don't need asynchronous operation, we just need a string [] array Can be completed 2. When we need asynchronous operation, we only need a complectionHandlerobj.ReturnObject property to collect objects.
code show as below://--------------------------------------------- ---- // Get Process Owner Info without the observer object // ---------------------------------- ---------------- // Createan Array Containing All Arguments for the methodstring [] 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.invokeMethod (Observer, "Getowner", NULL);
While (! companies "{system.threading.thread.sleep (500);
if (. completionHandlerObj.ReturnObject [ "returnValue"] ToString () == "0") structProcess.stringUserName = completionHandlerObj.ReturnObject.Properties [ "User"] Value.ToString ();. else structProcess.stringUserName = "";
Here are how to end the process:
Terminating a specified process is similar to the startup or termination of a service mentioned above. First of now, it is of course used to specify the process you want, and then call the InvokeMethod (Observer, "Terminate", null to terminate a process.
The following code: // Set up a handler for the asynchronous callbackManagementOperationObserver observer = new ManagementOperationObserver (); completionHandler.MyHandler completionHandlerObj = new completionHandler.MyHandler (); observer.ObjectReady = new ObjectReadyEventHandler (completionHandlerObj.Done);
// Get ManagementObject for processQueryCollection = getProcessCollection ("Select * from win32_process where processid = '" processid "'");
// statusupdatestatus ("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 timeoutint intCount = 0;! while (completionHandlerObj.IsComplete ) {IF (intcount == 10) {MessageBox.show ("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");}}
Create a process:
Creating a new process We need to call the ManagementClass class's InvokeMethod method to complete our can achieve a managementClassClassClassClass = New ManagementClassClassClass = New ManagementClassClassClass = New ManagementClass (MS, PATH, NULL); this statement is implemented to implement a managementclass object. MS is an instance of an ManagementsCope class; Path Is a managementPath instance. ManagementScope To set the range of management. ManagementPath is used to provide a package for analyzing and generating the path to WMI objects. ("Win32_Process") Before we need to call ManagementClass.invokeMethod (Observer, MethodName, . inParameters) we can pass to a four parameters .inParameters through an array of objects is actually a Create Method in Class Win32_Process (reference Platform SDK: Windows Management Instrumentation) uint32 Create (string CommandLine, string CurrentDirectory, Win32_ProcessStartup ProcessStartupInformation, uint32 * ProcessId ParametersCommandline - [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.ProcessStartupInformation -.. [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 worth it
Such as code: // crete an array containing all arguments for the methodObject [] methodargs = {stringcommandline, null, null, 0};
// Execute the MethodProcessClass.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"), this time you will You can create a calculator process, below is an example.
code show as below;
///
String stringmachinename = "";
// Connect to the remote computer ConnectionOptions co = new ConnectionOptions (); if (radioMachine.Checked == true) {stringMachineName = "localhost";} else {stringMachineName = textIP.Text;}
IF (StringMachnename.trim (). Length == 0) {MessageBox.show ("Must Enter Machine IP Address or Name); Return;}
// get user and password if (TextUserId.Text.trim (). Length> 0) {Co. HERNAME = 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 [] methodLine, NULL, NULL, 0};
// Execute The Method ProcessClassClass.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 Else {MessageBox.show ("Create New Process");}}} // status updatestatus ("ready"); this.Update ();}
Summary: This is just an example of using WMI. We can understand the WMI can do those things through this simple example. I think, the comments I am in the code can be very convenient to let everyone know WMI.
Below this list allows you to understand that WMI can handle those questions:
* Control your hardware and hardware * Regulatory Events * Execute an event-based description * Send E-mail through an event
Reference: [URL] http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/wmi_start_page.asp [/ url] [URL] http: // www .microsoft.com / Taiwan / TechNet / ScriptCenter / Sampscr.htm [/ URL]