Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

windows - Incorrect way of using a WMI Class c++

I am trying to make a function that shut downs the computer fan (if possible):

It should connect to a WMI Class, get the CIM_Fan class and call setPowerState function with parameter 6 (shutdown). I was following this tutorial but with little to no experience with this API I probably messed up. Here is the code:

// Connection to Windows:
    IWbemLocator* pLoc = 0;
    IWbemServices* pSvc = 0;
    HRESULT hr;
    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    hr =CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
    hr = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
    hr = pLoc->ConnectServer(BSTR(L"ROOT\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
    hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

    // Now getting the CIM_Fan object:
    BSTR MethodName = SysAllocString(L"SetPowerState");
    BSTR ClassName = SysAllocString(L"CIM_Fan");

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

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

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

    // Create the values for the in parameters
    VARIANT varCommand;
    varCommand.vt = VT_BSTR;
    varCommand.bstrVal = BSTR("6"); // Should send here the parameters ?

    // Store the value for the in parameters
    pClassInstance->Put(L"CommandLine", 0, &varCommand, 0);
    wprintf(L"The command is: %s
", V_BSTR(&varCommand));

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

    // Clean up
 //--------------------------
    VariantClear(&varCommand);
    SysFreeString(ClassName);
    SysFreeString(MethodName);
    pClass->Release();
    pClassInstance->Release();
    pInParamsDefinition->Release();
    pOutParams->Release();
    pLoc->Release();
    pSvc->Release();
    CoUninitialize();
question from:https://stackoverflow.com/questions/65641302/incorrect-way-of-using-a-wmi-class-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...