WMI(Windows Management Instrumentation)是Windows下可以与系统信息(包括软硬件等)的一个管理框架,通过WMI可以很方便地对机器进行管理。现在以通过WMI来打开(或创建)一个记事本(notepad.exe)进程为例,看看VC++到.Net的变迁,一览.Net是如何让程序员从繁琐晦涩的程序中解放出来。

1、预工作:
VC++中需要在源代码中加入:
#include <Wbemidl.h>
#pragma comment(lib, "wbemuuid.lib")

VC#中需要:
在工程中添加引用:System.Management
在代码中加入using System.Management;

2、流程:
VC++的代码,需要6步和查询返回值、最后释放资源:
None.gif// Step 1: --------------------------------------------------
None.gif
// Initialize COM. ------------------------------------------
None.gif
hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
None.gif

None.gif// Step 2: --------------------------------------------------
None.gif
// Set general COM security levels --------------------------
None.gif
hres =  CoInitializeSecurity(
None.gif        NULL, 
None.gif        
-1,                          // COM negotiates service
None.gif
        NULL,                        // Authentication services
None.gif
        NULL,                        // Reserved
None.gif
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
None.gif
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
None.gif
        NULL,                        // Authentication info
None.gif
        EOAC_NONE,                   // Additional capabilities 
None.gif
        NULL                         // Reserved
None.gif
        );

None.gif// Step 3: ---------------------------------------------------
None.gif
// Obtain the initial locator to WMI -------------------------
None.gif
IWbemLocator *pLoc = NULL;
None.gifhres 
= CoCreateInstance(
None.gif        CLSID_WbemLocator,             
None.gif        
0
None.gif        CLSCTX_INPROC_SERVER, 
None.gif        IID_IWbemLocator, (LPVOID 
*&pLoc);
None.gif

None.gif// Step 4: ---------------------------------------------------
None.gif
// Connect to WMI through the IWbemLocator::ConnectServer method
None.gif
IWbemServices *pSvc = NULL;
None.gif
// Connect to the local root\cimv2 namespace
None.gif
// and obtain pointer pSvc to make IWbemServices calls.
None.gif
hres = pLoc->ConnectServer(
None.gif        _bstr_t(L
"ROOT\\CIMV2"), 
None.gif        NULL,
None.gif        NULL, 
None.gif        
0
None.gif        NULL, 
None.gif        
0
None.gif        
0
None.gif        
&pSvc
None.gif    );
None.gif

None.gif// Step 5: --------------------------------------------------
None.gif
// Set security levels for the proxy ------------------------
None.gif
hres = CoSetProxyBlanket(
None.gif        pSvc,                        
// Indicates the proxy to set
None.gif
        RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx 
None.gif
        RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx 
None.gif
        NULL,                        // Server principal name 
None.gif
        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
None.gif
        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
None.gif
        NULL,                        // client identity
None.gif
        EOAC_NONE                    // proxy capabilities 
None.gif
    );

None.gif// Step 6: --------------------------------------------------
None.gif
// Use the IWbemServices pointer to make requests of WMI ----
None.gif
// set up to call the Win32_Process::Create method
None.gif
BSTR MethodName = SysAllocString(L"Create");
None.gifBSTR ClassName 
= SysAllocString(L"Win32_Process");
None.gif
None.gifIWbemClassObject
* pClass = NULL;
None.gifhres 
= pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
None.gif
None.gifIWbemClassObject
* pInParamsDefinition = NULL;
None.gifhres 
= pClass->GetMethod(MethodName, 0
None.gif        
&pInParamsDefinition, NULL);
None.gif
None.gifIWbemClassObject
* pClassInstance = NULL;
None.gifhres 
= pInParamsDefinition->SpawnInstance(0&pClassInstance);
None.gif
None.gif
// Create the values for the in parameters
None.gif
VARIANT varCommand;
None.gifvarCommand.vt 
= VT_BSTR;
None.gifvarCommand.bstrVal 
= L"notepad.exe";
None.gif
// Store the value for the in parameters
None.gif
hres = pClassInstance->Put(L"CommandLine"0,
None.gif        
&varCommand, 0);
None.gifwprintf(L
"The command is: %s\n", V_BSTR(&varCommand));
None.gif
None.gif
// Execute Method
None.gif
IWbemClassObject* pOutParams = NULL;
None.gifhres 
= pSvc->ExecMethod(ClassName, MethodName, 0, NULL, pClassInstance, &pOutParams, NULL);
None.gif

None.gif// Get return value
None.gif
VARIANT varReturnValue;
None.gifhres 
= pOutParams->Get(_bstr_t(L"ReturnValue"), 0&varReturnValue, NULL, 0);
None.gif
None.gif
// Last: clean up
None.gif
VariantClear(&varCommand);
None.gifVariantClear(
&varReturnValue);
None.gifSysFreeString(ClassName);
None.gifSysFreeString(MethodName);
None.gifpClass
->Release();
None.gifpInParamsDefinition
->Release();
None.gifpOutParams
->Release();
None.gifpLoc
->Release();
None.gifpSvc
->Release();
None.gifCoUninitialize();

VC#只需寥寥数行就可以实现(暂不考虑错误处理):
跳过VC++中的Step1~5,直接从Step6开始。而且非常直观:
None.gifManagementClass mc = new  ManagementClass("Win32_Process");
None.gifManagementBaseObject obj 
= mc.GetMethodParameters("Create");
None.gifobj[
"CommandLine"]="notepad.exe";
None.gifmc.InvokeMethod(
"Create", obj, null);
None.gifmc.Dispose();None.gif

.Net对WMI良好的封装,还有对字符串的更强支持、方便的垃圾回收机制,使程序既一目了然,又易于维护。其实类似的区别在VC vs VB年代已经出现了(特别是在COM组件编写和调用方面可以看出),从这点也可以看出.Net完全继承了VB易学易用的特性,又不失强大的功能。