EnumWindows

#include <Tlhelp32.h>
#include <windows.h>

#include <iostream>
#include <iomanip>
#include <map>
#include <string>
using namespace std;

map<DWORD, wstring> GetProcessIdAndName()
{
    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    PROCESSENTRY32 pe32 = {};
    pe32.dwSize = sizeof(PROCESSENTRY32);
    map<DWORD, wstring> idName;            // '.first' is process ID, '.second' is process name.
    
    // Travel all processes.
    if (Process32First(hSnapshot, &pe32))
    {
        do 
        {
            idName[pe32.th32ProcessID] = pe32.szExeFile;
        } while (Process32Next(hSnapshot, &pe32));
    }

    CloseHandle(hSnapshot);

    return idName;
}


BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    DWORD pid = 0;
    map<DWORD, wstring> &idNames = *reinterpret_cast<map<DWORD, wstring> *>(lParam);
    GetWindowThreadProcessId(hWnd, &pid);

    map<DWORD, wstring>::iterator wndProcess;
    if ((wndProcess = idNames.find(pid)) != idNames.end())
    {
        wcout <<setw(10) <<wndProcess->second <<L"\t:\t" <<wndProcess->first <<endl;
    }
    else
    {
        wcout <<L"Error: " <<pid <<endl;
    }


    return TRUE;
}



void _tmain(int argc, TCHAR *argv[])
{
    map<DWORD, wstring> idNames = GetProcessIdAndName();
    EnumWindows(EnumWindowsProc, reinterpret_cast<LPARAM>(&idNames));
    
    return;
}
posted @ 2012-08-12 19:42  walfud  阅读(374)  评论(0编辑  收藏  举报