首页 > 代码库 > Window获取所有运行的进程

Window获取所有运行的进程

通过遍历任务管理器,输出当前正在运行的进程ID和Name。

同时打印出遍历过程所消耗的时间。

/*
@Date:2014/6/8
@Author:Alex
*/

#include <iostream>
#include <string>  
#include <map>  
#include <windows.h>  
#include <TlHelp32.h>
using namespace std;

bool traverseProcesses(map<std::wstring,int> &_mapProcess)
{
    PROCESSENTRY32 pe32;  
    pe32.dwSize = sizeof(pe32);  
  
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);  
    if(hProcessSnap == INVALID_HANDLE_VALUE) {  
        std::cout << "CreateToolhelp32Snapshot Error!" << std::endl;;  
        return false;  
    }  
  
    BOOL bResult =Process32First(hProcessSnap, &pe32);  
  
    int num(0);  
	
    while(bResult)   
    {  
		std::wstring name = pe32.szExeFile;  
        int id = pe32.th32ProcessID;  
 
		std::cout << "[" << ++num << "]: "<< "--ProcessID:" << id;  

		std::wcout<<"--Process Name:" << name<<endl;
  
        _mapProcess.insert(std::pair<wstring, int>(name, id)); //字典存储  
        bResult = Process32Next(hProcessSnap,&pe32);  
    }  
  
    CloseHandle(hProcessSnap);  
    return true;  
}
int main(int argc, char*argv[])
{
	map<std::wstring,int> mapProcess;
	
	DWORD start = ::GetTickCount();
	traverseProcesses(mapProcess);
	
	DWORD end = ::GetTickCount();
	cout<<"waste time:"<<end-start<<endl;
	getchar();
	return 0;
}