#include <Wbemidl.h>
#pragma comment(lib,"Wbemuuid.lib")
HRESULT XXXDialog::EnableDHCPOnAdapter()
{
hr = CoInitializeEx(0, COINIT_MULTITHREADED);
hr = CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_PKT_PRIVACY,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,EOAC_SECURE_REFS,NULL);
HRESULT hr;
IWbemLocator *pLocator = NULL;
IWbemServices *pNamespace = NULL;
IWbemClassObject *pClass = NULL;
IWbemClassObject *pInputParamClass = NULL;
IWbemClassObject *pInputParamInstance = NULL;
IWbemClassObject *pOutInst = NULL;
BSTR InstancePath = SysAllocString(L"Win32_NetworkAdapterConfiguration.Index=8"); //index为网卡号
BSTR Path = SysAllocString(L"root\\cimv2");
BSTR ClassPath = SysAllocString(L"Win32_NetworkAdapterConfiguration");
BSTR MethodName1 = SysAllocString(L"SetDNSServerSearchOrder");
BSTR MethodName2 = SysAllocString(L"EnableDHCP");
LPCWSTR MethodName1ArgName = L"DNSServerSearchOrder";
hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (void **)&pLocator);
hr = pLocator->ConnectServer(Path,NULL, NULL, NULL, 0, NULL, NULL, &pNamespace);
hr = CoSetProxyBlanket( pNamespace,
RPC_C_AUTHN_WINNT,
RPC_C_AUTHZ_NONE,
NULL,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
if(SUCCEEDED(hr))
hr = pNamespace->GetObject(ClassPath, 0, NULL, &pClass, NULL);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
if(SUCCEEDED(hr))
hr = pClass->GetMethod(MethodName1, 0, &pInputParamClass, NULL);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
if(SUCCEEDED(hr))
hr = pInputParamClass->SpawnInstance(0, &pInputParamInstance);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
if(SUCCEEDED(hr))
hr = pInputParamInstance->Put(MethodName1ArgName, 0, NULL, 0);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
if(SUCCEEDED(hr))
hr = pNamespace->ExecMethod(InstancePath, MethodName1, 0, NULL, pInputParamInstance, &pOutInst, NULL);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
if(SUCCEEDED(hr))
hr = pNamespace->ExecMethod(InstancePath, MethodName2, 0, NULL, NULL, &pOutInst, NULL);
if(!SUCCEEDED(hr))
{
PrintWMIError(hr);
return hr;
}
SysFreeString(InstancePath);
SysFreeString(Path);
SysFreeString(ClassPath);
SysFreeString(MethodName1);
SysFreeString(MethodName2);
if(pOutInst)
pOutInst->Release();
if(pInputParamInstance)
pInputParamInstance->Release();
if(pInputParamClass)
pInputParamClass->Release();
if(pClass)
pClass->Release();
if(pNamespace)
pNamespace->Release();
if(pLocator)
pLocator->Release();
CoUninitialize();
return hr;
}