Using Win32_Process WMI class
A previous article shows how to use Win32_PhysicalMedia WMI class to get physical drive info. We can write something similar for getting a list of running processes. All we have to do is to replace the WQL query and get specific properties for Win32_Process. However, to simplify the things, I wrote few C++ wrapper classes over the WMI stuff.
Here is a brief description for each one:
- CWMIConnection – opens and keeps a connection to WMI namespace.
- CWMIQuery – executes WQL (SQL for WMI) queries and navigates through results.
- CWMIWin32_Process – is derived from CWMIQuery and is specialized for Win32_Process.
- CWMIValue – a class that gets user readable strings from different CIM types.
The implementation details can be found in the attached demo project.
Let’s show now just a usage example, that fills a list-view control with info about running processes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
void CDemoDlg::_FillProcessesList() { // clear listview control m_listProcesses.DeleteAllItems(); try { // Open WMI connection CWMIConnection wmiConnection; wmiConnection.Open(L"ROOT\\CIMV2"); // Query Win32_Process CWMIWin32_Process wmiQuery(wmiConnection); wmiQuery.Open(); // Fill the list int nItem = 0; while(wmiQuery.MoveNext()) { m_listProcesses.InsertItem(nItem, NULL); m_listProcesses.SetItemText(nItem, ePID, WMI_GETPROPERTYSTR(wmiQuery, Handle)); m_listProcesses.SetItemText(nItem, eSessionID, WMI_GETPROPERTYSTR(wmiQuery, SessionId)); m_listProcesses.SetItemText(nItem, eImageName, WMI_GETPROPERTYSTR(wmiQuery, Caption)); m_listProcesses.SetItemText(nItem, eCommandLine, WMI_GETPROPERTYSTR(wmiQuery, CommandLine)); // ... // NOTE: This is just for demo purpose and can be completed. // For a compelte list of Win32_Process properties, see MSDN documentation. // http://msdn.microsoft.com/en-us/library/aa394372%28v=vs.85%29.aspx nItem++; } } catch(COleException* e) { e->ReportError(); e->Delete(); } } |
Demo project
The demo project is a simple MFC dialog-based application that uses WMI wrapper classes to list and get info about running processes.
Download: Listing_Processes__Using_WMI.zip (1769)
Resources
- MSDN: Win32_Process class
- MSDN: WQL (SQL for WMI)
See also
- Codexpert blog: Listing Processes – Part 1: Introduction
- Codexpert blog: Listing Processes – Part 2: Using PSAPI
- Codexpert blog: Listing Processes – Part 3: Using Tool Help Library
- Codexpert blog: Listing Processes – Part 4: Using Remote Desktop Services API
- Codexpert blog: Get Physical Drive Serial Number – Part 2