-
June 8th, 2014, 07:57 AM
#1
WinAPI: How to enumerate processes?
Q: How to enumerate currently running processes?
A: One method is by using Process Status API (PSAPI).
Example
Code:
#include <list>
#include <iostream>
#include <Windows.h>
#include <Psapi.h>
#pragma comment(lib, "Psapi.lib")
// Note: linking to Psapi.lib is not necessary if the target system is Windows 7 or newer
DWORD PSAPI_EnumProcesses(std::list<DWORD>& listProcessIDs, DWORD dwMaxProcessCount)
{
DWORD dwRet = NO_ERROR;
listProcessIDs.clear();
DWORD *pProcessIds = new DWORD[dwMaxProcessCount];
DWORD cb = dwMaxProcessCount * sizeof(DWORD);
DWORD dwBytesReturned = 0;
// call PSAPI EnumProcesses
if (::EnumProcesses(pProcessIds, cb, &dwBytesReturned))
{
// push returned process IDs into the output list
const int nSize = dwBytesReturned / sizeof(DWORD);
for(int nIndex = 0; nIndex < nSize; nIndex++)
{
listProcessIDs.push_back(pProcessIds[nIndex]);
}
}
else
{
dwRet = ::GetLastError();
}
delete[]pProcessIds;
return dwRet;
}
Code:
int main()
{
std::list<DWORD> listProcessIDs;
const DWORD dwMaxProcessCount = 1024;
DWORD dwRet = PSAPI_EnumProcesses(listProcessIDs, dwMaxProcessCount);
if(NO_ERROR == dwRet)
{
const std::list<DWORD>::const_iterator end = listProcessIDs.end();
std::list<DWORD>::const_iterator iter = listProcessIDs.begin();
for( ; iter != end; ++iter)
{
DWORD dwProcessID = *iter;
std::cout << "Process ID: " << dwProcessID << std::endl;
// NOTE: you can pass dwProcessID to ::OpenProcess and further get
// more process info by using the returned process handle
}
}
else
{
std::cout << "PSAPI_GetProcessesList failed. Error: " << dwRet << std::endl;
return dwRet;
}
return 0;
}
Resources and related articles
Last edited by ovidiucucu; June 8th, 2014 at 09:01 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|