STL functors, scoped handles and how we can use them in Windows programming - example of usage
#include "stdafx.h"
#include <iostream>
#include "scoped_handle.h"
using namespace std;
// Implementation of "countof" obtained from https://blogs.msdn.com/the1/archive/2004/05/07/128242.aspx
template <typename T, size_t N>
char (&_ArraySizeHelper(T (&array)[N]))[N];
#define countof(array) (sizeof(_ArraySizeHelper(array)))
int _tmain(int argc, _TCHAR* argv[])
{
DWORD rProcessIds[256];
DWORD cbReturned;
if (0 == ::EnumProcesses(rProcessIds, sizeof(rProcessIds), &cbReturned) || cbReturned == sizeof(rProcessIds))
{
cout << "EnumProcesses failed" << endl;
return 1;
}
DWORD cProcesses = cbReturned / sizeof(DWORD);
char szName[256];
for (DWORD i = 0; i < cProcesses; ++i)
{
DWORD dwProcessId = rProcessIds[i];
// Skip process ID 0.
if (0 == dwProcessId)
continue;
scoped_handle<HANDLE, NULL> handle(NULL, ::CloseHandle);
handle = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, dwProcessId);
if (!handle)
{
DWORD dwError = ::GetLastError();
// Skip inaccessible processes.
if (ERROR_ACCESS_DENIED == dwError)
continue;
cout << "OpenProcess failed with " << dwError << endl;
return 1;
}
DWORD cchName = countof(szName);
if (0 == ::QueryFullProcessImageNameA(handle, 0, szName, &cchName))
{
cout << "QueryFullProcessImageName failed with " << ::GetLastError() << endl;
continue;
}
cout << szName << endl;
}
return 0;
}
Comments
- Anonymous
November 04, 2008
Firstly, it's election day so get out there and vote! Secondly, I went to bed last night and dreamt about