Click here to Skip to main content
6,596,602 members and growing! (22,571 online)
Email Password   helpLost your password?
General Reading » Hardware & System » General     Intermediate License: The Code Project Open License (CPOL)

Getting Information from WMI in Visual C++

By Aamir Butt

This is an Article just to describe how to use WMI with Visual C++ 6. I had to do this for one of my projects and I finally came up with this solution. I hope this will be beneficial to others as well.
VC6, VC7.1Win2K, ATL, VS.NET2003, Dev
Posted:14 Jan 2004
Updated:23 Jun 2004
Views:164,795
Bookmarked:36 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
28 votes for this article.
Popularity: 5.16 Rating: 3.57 out of 5
2 votes, 7.1%
1
4 votes, 14.3%
2
1 vote, 3.6%
3
2 votes, 7.1%
4
19 votes, 67.9%
5

Introduction

We normally find a lot of ways and a number of resources to use WMI or to get information from �Windows Management Instrumentation� while using Visual Basic 6 and C#, but I could not find a single resource describing the same thing in Visual C++. MSDN resources are also very limited in this context.

Code

Following is the code on how to get the current processor load from a WMI class Win32_Processor defined in a .mof file. .mof files are managed object files which have a typical way of defining classes and methods.

WMI provides the COM service which is used to connect to the WMI services. The important parts of the code include:

  • bstrNamespace : The initialization of this variable is very tricky. The first three forward slashes //./ represent the Host Computer name from which you want to get information from. A �.� Indicates that information is to be obtained from the Same Computer on which you are working. You can give any Network name here but getting information from network depends upon your Access Rights etc. cimv2 is the namespace containing the Win32_Processor class.
  • pIWbemLocator is the argument in which we get the Interface pointer.
  • After that, we call the function ConnectServer of the pIWbemLocator to get a pointer to pWbemServices.
  • WMI uses its own Query Language to get information known as WQL (the acronym for WMI Query Language). So, when calling the function ExecQuery, we have to specify the language as its first argument. Second argument is the Query itself. Last argument is important because here we get a pointer to an Enumeration object through which we can enumerate through the objects available. This enumeration is important because consider the case that we want to know the information about running processes and we are using Win32_Process class for this purpose. Then through this enumeration object, we can go through different processes one by one.
  • By calling the Reset and Next methods of pEnumObject, we are moving through the objects. We get the pointer to an object in pClassObject.
  • The last function through which we get the Actual value of a property is Get. We pass a BSTR to this function to get the value in a Variant.
CoInitialize(NULL);

//Security needs to be initialized in XP first 


if(CoInitializeSecurity( NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
EOAC_NONE,
0
) != S_OK)
    return;

IWbemLocator * pIWbemLocator = NULL;
IWbemServices * pWbemServices = NULL;
IEnumWbemClassObject * pEnumObject = NULL;
BSTR bstrNamespace = (L"root\\cimv2");
HRESULT hRes = CoCreateInstance (
  CLSID_WbemAdministrativeLocator,
  NULL ,
  CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER , 
  IID_IUnknown ,
  ( void ** ) & pIWbemLocator
  ) ;
if (SUCCEEDED(hRes))
{
  hRes = pIWbemLocator->ConnectServer(
  bstrNamespace, // Namespace

  NULL, // Userid

  NULL, // PW

  NULL, // Locale

  0, // flags

  NULL, // Authority

  NULL, // Context

  &pWbemServices
  );
}
BSTR strQuery = (L"Select * from win32_Processor");
BSTR strQL = (L"WQL");
hRes = pWbemServices->ExecQuery(strQL, strQuery,
  WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);

ULONG uCount = 1, uReturned;
IWbemClassObject * pClassObject = NULL;
hRes = pEnumObject->Reset();
hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
VARIANT v;
BSTR strClassProp = SysAllocString(L"LoadPercentage");
hRes = pClassObject->Get(strClassProp, 0, &v, 0, 0);
SysFreeString(strClassProp);

_bstr_t bstrPath = &v; //Just to convert BSTR to ANSI

char* strPath=(char*)bstrPath;
if (SUCCEEDED(hRes))
MessageBox(strPath);
else
MessageBox(�Error in getting object�);
VariantClear( &v );
pIWbemLocator->Release();
pWbemServices->Release();
pEnumObject->Release();
pClassObject->Release();
CoUninitialize();

Conclusion

This was the shortest method I was able to work out to get information from any WMI class. You can simply change the class name in the Query and Property Name while calling Get method and you will get information from all the classes supported in your OS. I tested this code in Windows 2000 Professional. I hope it will work well for Win XP but probably not in previous versions of windows because they don�t support a lot of WMI classes.

Update

I am updating this Article and the code for Windows XP. As I said in the beginning, this was initially intended for Windows 2K and it was still working fine on Windows 2K machine (I have checked it on at least 10 now coz I was getting so many complaints). Well, for Windows XP there is one major change and that was suggested by igoychev. Many thanks for that. The problem with Windows XP was that it needed security to be initialized first. Plus, I have also changed those confusing slashes in bstrNamespace to some simpler ones. I am using Windows 2003 Advance Server and it is working fine on it. You need to include wbemuuid.lib in Project Settings -> Linker -> Additional Dependencies to get this code working. I have also added some error checking to avoid crashes, hope it works for you. You need to have Platform SDK installed for this code to compile. WMI SDK is not necessary once again. Sorry rbervgm, your work was great using WMI SDK but I thought better to keep it WMI SDK Clean. Hope you don't mind. Now, I hope that downloadable project will work for most of the people. One more thing, it still works for Windows 2K machines.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Aamir Butt


Member
Nothing special. Just a normal person living a normal life. Programming in office and Football(soccer) at home. That's all my life is about.

My Articles
Occupation: Software Developer (Senior)
Location: Pakistan Pakistan

Other popular Hardware & System articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 115 (Total in Forum: 115) (Refresh)FirstPrevNext
GeneralError while compiling PinmemberBhaskartrivedi9:32 25 Aug '08  
GeneralRe: Error while compiling PinmemberPriya_Sundar1:59 1 Apr '09  
GeneralMissing code.. PinmemberChizI6:08 23 May '08  
GeneralUnable to make remote Connection Pinmemberanushka.babu23:33 16 Apr '08  
Generalnot working under win 2k env Pinmemberbhanu_codeproject20:49 21 Nov '07  
GeneralRe: not working under win 2k env PinmemberUserMarcus4:02 24 Sep '08  
GeneralRe: not working under win 2k env PinmemberUserMarcus5:22 2 Oct '08  
GeneralIn the first attenpt itself it has worked Pinmemberbhanu_codeproject0:47 21 Nov '07  
GeneralHow to call WMI in MFC Externsion DLL Pinmemberyoungkwan song22:03 30 Aug '07  
GeneralAccessing IE settings in Vista PinmemberDana Daugherty23:10 11 Jun '07  
GeneralMissing DLL and header files PinmemberPeterLeblang2:54 22 Jan '07  
GeneralRe: Missing DLL and header files PinmemberAamir Butt19:26 22 Jan '07  
GeneralHelp me please to recognize situation by using WMI Pinmembermaria.net4:07 7 Aug '06  
QuestionI got the same error Pinmemberhoker.ffb0:34 4 Jul '06  
General#define _WIN32_DCOM PinmemberSpitfireX2:57 16 May '06  
GeneralRe: #define _WIN32_DCOM Pinmembertyjjrtruy4teqye7nyue7qay21:33 8 Jan '07  
GeneralRe: #define _WIN32_DCOM Pinmemberti-oh0:28 17 Jan '07  
GeneralIP Address Pinmemberdianalexander22:19 9 Feb '06  
GeneralRe: IP Address PinmemberAamir Butt18:24 12 Feb '06  
GeneralRe: IP Address Pinmembermcxiand21:58 15 May '06  
GeneralRe: IP Address PinmemberOrkblutt3:32 5 Oct '06  
Generalunhandled Win32 exception PinmemberIronic26622:27 23 Nov '05  
GeneralRe: unhandled Win32 exception PinmemberAamir Butt19:45 24 Nov '05  
GeneralRe: unhandled Win32 exception PinmemberIronic26623:32 26 Nov '05  
GeneralConnect to several namespaces Pinmemberangelzoo3:39 14 Nov '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jun 2004
Editor: Nishant Sivakumar
Copyright 2004 by Aamir Butt
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project