從WMI看VC++到.Net的變遷

來源:互聯網
上載者:User
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步和查詢傳回值、最後釋放資源: // Step 1: --------------------------------------------------
// Initialize COM. ------------------------------------------
hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 

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

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

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

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

// Step 6: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----
// set up to call the Win32_Process::Create method
BSTR MethodName = SysAllocString(L"Create");
BSTR ClassName = SysAllocString(L"Win32_Process");

IWbemClassObject* pClass = NULL;
hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);

IWbemClassObject* pInParamsDefinition = NULL;
hres = pClass->GetMethod(MethodName, 0, 
        &pInParamsDefinition, NULL);

IWbemClassObject* pClassInstance = NULL;
hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);

// Create the values for the in parameters
VARIANT varCommand;
varCommand.vt = VT_BSTR;
varCommand.bstrVal = L"notepad.exe";
// Store the value for the in parameters
hres = pClassInstance->Put(L"CommandLine", 0,
        &varCommand, 0);
wprintf(L"The command is: %s\n", V_BSTR(&varCommand));

// Execute Method
IWbemClassObject* pOutParams = NULL;
hres = pSvc->ExecMethod(ClassName, MethodName, 0, NULL, pClassInstance, &pOutParams, NULL);

// Get return value
VARIANT varReturnValue;
hres = pOutParams->Get(_bstr_t(L"ReturnValue"), 0, &varReturnValue, NULL, 0);

// Last: clean up
VariantClear(&varCommand);
VariantClear(&varReturnValue);
SysFreeString(ClassName);
SysFreeString(MethodName);
pClass->Release();
pInParamsDefinition->Release();
pOutParams->Release();
pLoc->Release();
pSvc->Release();
CoUninitialize();

VC#只需寥寥數行就可以實現(暫不考慮錯誤處理):
跳過VC++中的Step1~5,直接從Step6開始。而且非常直觀: ManagementClass mc = new  ManagementClass("Win32_Process");
ManagementBaseObject obj = mc.GetMethodParameters("Create");
obj["CommandLine"]="notepad.exe";
mc.InvokeMethod("Create", obj, null);
mc.Dispose();

.Net對WMI良好的封裝,還有對字串的更強支援、方便的記憶體回收機制,使程式既一目瞭然,又易於維護。其實類似的區別在VC vs VB年代已經出現了(特別是在COM組件編寫和調用方面可以看出),從這點也可以看出.Net完全繼承了VB易學易用的特性,又不失強大的功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.