例如代码:
//Create an array containing all arguments for the method
object methodArgs = {stringCommandLine, null, null, 0};
//Execute the method
processClass.InvokeMethod (observer, "Create", methodArgs);
下面的代码是用来创建并插入一个新的进程.我们可以写一个CreateProcess
函数通过参数stringCommandLine来传递一个你希望创建的进程.如你可以
这样写 CreateProcess("Calc.exe"), 这时候你就可以创建一个计算器
进程了,下面是个例子.
代码如下;
/// <summary>
/// Invoke method ''Create'' on local or remote machine
/// </summary>
///
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();
}
总结:
这里只是做了一个使用WMI的例子.我们大体可以通过这个简单的例子
了解一下WMI究竟可以做那些