Click here to Skip to main content
11,708,721 members (72,561 online)
Click here to Skip to main content

Getting Information from WMI in Visual C++

, 27 Sep 2011 CPOL 337.5K 10.6K 69
Rate this:
Please Sign up or sign in to vote.
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.

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 the 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.

The code for getting Processor Load is in a thread which keeps on running and posts message to UI to update the Progress bar. Here is the Thread function.

UINT GetProcessorLoad( LPVOID pParam )
{
	CUsingWMIDlg* dlg = (CUsingWMIDlg*)pParam;
	
	CoInitialize(NULL);

	HRESULT hRes = CoInitializeSecurity( NULL, -1, NULL, 
		NULL, RPC_C_AUTHN_LEVEL_PKT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL,
		EOAC_NONE, 0);

	if(hRes != S_OK) return 0;

	CComPtr<iwbemlocator> pIWbemLocator;
	CComPtr<iwbemservices> pIWbemServices;
	CComPtr<ienumwbemclassobject> pIEnumObject;

	CComBSTR bstrNamespace(_T("root\\cimv2"));

	hRes = pIWbemLocator.CoCreateInstance(CLSID_WbemAdministrativeLocator);
	if(hRes != S_OK) return 0;

	hRes = pIWbemLocator->ConnectServer(bstrNamespace, NULL, 
		NULL, NULL, 0, NULL, NULL, &pIWbemServices);
	if(hRes != S_OK) return 0;

	while(true)
	{
		CComBSTR bstrQuery(_T("Select * from Win32_Processor"));
		CComBSTR bstrQL(_T("WQL"));

		hRes = pIWbemServices->ExecQuery
		(bstrQL, bstrQuery, WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pIEnumObject);

		ULONG uCount = 1, uReturned;
		CComPtr<iwbemclassobject> pIClassObject;

		hRes = pIEnumObject->Reset();

		hRes = pIEnumObject->Next
		(WBEM_INFINITE, uCount, &pIClassObject, &uReturned);

		if(hRes != S_OK) return 0;

		CComVariant var;

		CComBSTR bstrProp(_T("LoadPercentage"));

		hRes = pIClassObject->Get(bstrProp, 0, &var, NULL, NULL);
		if(hRes != S_OK) return 0;

		int * value = new int(var.lVal);
		dlg->PostMessage(WM_USER+1, (WPARAM) value);
		
		pIEnumObject.Release();
	}
	return 1;
}

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 have now tested this code in Windows 7, Windows XP, Win2000, Win2003 and Win2008.

Update

I found out that the code associated with this article was very badly written. After all, I did this when I was a student. Now that I know a tiny bit more, I am updating the code. I have now used Smart Pointers and I have also updated the example App to show the Processor load in a Progress Bar. Furthermore, this is now a Visual Studio 2008 project.
Another fix was to add a lib file in linker settings.

License

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

Share

About the Author

Aamir Butt
Technical Lead
Pakistan Pakistan
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralWeak Code Pin
Elmue2-Sep-10 16:45
mvpElmue2-Sep-10 16:45 
Hello

Very strange:
Sometimes it works, sometimes it crashes. (on XP SP2, VS 2003)

In CUsingWMIDlg::OnButtonGetinfo()
The code
VARIANT v;
BSTR strClassProp = SysAllocString(L"LoadPercentage");
hRes = pClassObject->Get(strClassProp, 0, &v, 0, 0);

returns a
v which is VT_I4 (integer) with a value of 100 when it works and a
v which is VT_NULL when it does not work, which results in a crash.
Although in BOTH cases Get() had returned S_OK !!

VERY strange!

When I replace "LoadPercentage" with "Manufacturer" it works ALWAYS.
It seems that WMI is unusable due to severe MS$ bugs!
Additionally WMI is very slow!

You cannot trust solely on HRESULT, you must also check the returned Variant!

Elmü


GeneralRe: Weak Code [modified] Pin
Blake Miller22-Sep-10 11:26
memberBlake Miller22-Sep-10 11:26 
GeneralRe: Weak Code Pin
Elmue22-Sep-10 15:34
mvpElmue22-Sep-10 15:34 
GeneralError while compiling Pin
Bhaskartrivedi25-Aug-08 8:32
memberBhaskartrivedi25-Aug-08 8:32 
GeneralRe: Error while compiling Pin
Priya_Sundar1-Apr-09 0:59
memberPriya_Sundar1-Apr-09 0:59 
GeneralMissing code.. Pin
ChizI23-May-08 5:08
memberChizI23-May-08 5:08 
GeneralUnable to make remote Connection Pin
anushka.babu16-Apr-08 22:33
memberanushka.babu16-Apr-08 22:33 
Generalnot working under win 2k env Pin
bhanu_codeproject21-Nov-07 19:49
memberbhanu_codeproject21-Nov-07 19:49 
GeneralRe: not working under win 2k env Pin
UserMarcus24-Sep-08 3:02
memberUserMarcus24-Sep-08 3:02 
GeneralRe: not working under win 2k env Pin
UserMarcus2-Oct-08 4:22
memberUserMarcus2-Oct-08 4:22 
GeneralIn the first attenpt itself it has worked Pin
bhanu_codeproject20-Nov-07 23:47
memberbhanu_codeproject20-Nov-07 23:47 
QuestionHow to call WMI in MFC Externsion DLL Pin
youngkwan song30-Aug-07 21:03
memberyoungkwan song30-Aug-07 21:03 
GeneralAccessing IE settings in Vista Pin
Dana Daugherty11-Jun-07 22:10
memberDana Daugherty11-Jun-07 22:10 
GeneralMissing DLL and header files Pin
PeterLeblang22-Jan-07 1:54
memberPeterLeblang22-Jan-07 1:54 
GeneralRe: Missing DLL and header files Pin
Aamir Butt22-Jan-07 18:26
memberAamir Butt22-Jan-07 18:26 
GeneralHelp me please to recognize situation by using WMI Pin
maria.net7-Aug-06 3:07
membermaria.net7-Aug-06 3:07 
QuestionI got the same error Pin
hoker.ffb3-Jul-06 23:34
memberhoker.ffb3-Jul-06 23:34 
General#define _WIN32_DCOM Pin
SpitfireX16-May-06 1:57
memberSpitfireX16-May-06 1:57 
GeneralRe: #define _WIN32_DCOM Pin
tyjjrtruy4teqye7nyue7qay8-Jan-07 20:33
membertyjjrtruy4teqye7nyue7qay8-Jan-07 20:33 
GeneralRe: #define _WIN32_DCOM Pin
ti-oh16-Jan-07 23:28
memberti-oh16-Jan-07 23:28 
GeneralIP Address Pin
dianalexander9-Feb-06 21:19
memberdianalexander9-Feb-06 21:19 
GeneralRe: IP Address Pin
Aamir Butt12-Feb-06 17:24
memberAamir Butt12-Feb-06 17:24 
GeneralRe: IP Address Pin
mcxiand15-May-06 20:58
membermcxiand15-May-06 20:58 
GeneralRe: IP Address Pin
Orkblutt5-Oct-06 2:32
memberOrkblutt5-Oct-06 2:32 
Generalunhandled Win32 exception Pin
Ironic26623-Nov-05 21:27
memberIronic26623-Nov-05 21:27 
GeneralRe: unhandled Win32 exception Pin
Aamir Butt24-Nov-05 18:45
memberAamir Butt24-Nov-05 18:45 
GeneralRe: unhandled Win32 exception Pin
Ironic26626-Nov-05 22:32
memberIronic26626-Nov-05 22:32 
GeneralConnect to several namespaces Pin
angelzoo14-Nov-05 2:39
memberangelzoo14-Nov-05 2:39 
GeneralRe: Connect to several namespaces Pin
Aamir Butt24-Nov-05 18:53
memberAamir Butt24-Nov-05 18:53 
GeneralRe: Connect to several namespaces Pin
angelzoo24-Nov-05 22:09
memberangelzoo24-Nov-05 22:09 
QuestionMissing CoInitializeSecurity? Pin
tikcireviva27-Sep-05 0:34
membertikcireviva27-Sep-05 0:34 
AnswerRe: Missing CoInitializeSecurity? Pin
Aamir Butt24-Nov-05 18:55
memberAamir Butt24-Nov-05 18:55 
GeneralRe: Missing CoInitializeSecurity? Pin
keithlee27-Feb-06 9:50
memberkeithlee27-Feb-06 9:50 
AnswerRe: Missing CoInitializeSecurity? Pin
xiaozhijian11-Jan-06 20:44
memberxiaozhijian11-Jan-06 20:44 
GeneralRe: Missing CoInitializeSecurity? Pin
Zenith6315-Jul-07 9:17
memberZenith6315-Jul-07 9:17 
GeneralRe: Missing CoInitializeSecurity? Pin
Member 376488919-Jul-11 18:14
memberMember 376488919-Jul-11 18:14 
Questionhow to connect romote host Pin
wesley424812-May-05 15:36
memberwesley424812-May-05 15:36 
AnswerRe: how to connect romote host Pin
Aamir Butt24-Nov-05 19:01
memberAamir Butt24-Nov-05 19:01 
Generalwbemuuid.lib - CoCreateInstance problem Pin
viswanath_jntu9-Mar-05 19:13
memberviswanath_jntu9-Mar-05 19:13 
GeneralRe: wbemuuid.lib - CoCreateInstance problem Pin
Peter Beecken18-Nov-05 2:44
memberPeter Beecken18-Nov-05 2:44 
GeneralRe: wbemuuid.lib - CoCreateInstance problem Pin
JNygren11-Apr-07 5:37
memberJNygren11-Apr-07 5:37 
GeneralRe: wbemuuid.lib - CoCreateInstance problem Pin
pilixuanke8-May-07 3:09
memberpilixuanke8-May-07 3:09 
Generalwbemuuid.lib - error :object file corrupted Pin
viswanath_jntu9-Mar-05 18:06
memberviswanath_jntu9-Mar-05 18:06 
GeneralWin32_OperatingSystem Pin
<<Steff>>7-Mar-05 6:10
member<>7-Mar-05 6:10 
GeneralRe: Win32_OperatingSystem Pin
smartceo6-Jun-07 20:05
membersmartceo6-Jun-07 20:05 
GeneralRe: Win32_OperatingSystem Pin
don_francc15-Sep-10 19:32
memberdon_francc15-Sep-10 19:32 
Generalwin2k error!!! Pin
iicastle30-Jan-05 22:07
memberiicastle30-Jan-05 22:07 
GeneralRe: win2k error!!! Pin
Aamir Butt30-Jan-05 22:14
memberAamir Butt30-Jan-05 22:14 
GeneralProblem under Win2K Pin
AxelHecker3-Jan-05 4:38
memberAxelHecker3-Jan-05 4:38 
Questionwhere to get Wbemcli.h? Pin
alfredosp6-Oct-04 9:08
memberalfredosp6-Oct-04 9:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 27 Sep 2011
Article Copyright 2004 by Aamir Butt
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid