通过清心醉

C++获取所有进程ID和名称

主要通过快照遍历方式

#include<iostream>
#include<string>
#include<windows.h>
#include<vector>
#include<winuser.h>
#include<Tlhelp32.h>
#include<algorithm>
using namespace std;
struct ProcessInfo
{
	DWORD PID;
	string PName;
	ProcessInfo(DWORD PID, string PNmae) : PID(PID), PName(PNmae) {}

	//排序条件:PID 从小到大降序
	bool operator < (const ProcessInfo& rhs) const {
		return (PID < rhs.PID);
	}
};
// WCHAR 转换为 std::string
string WCHAR2String(LPCWSTR pwszSrc)
{
	int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL);
	if (nLen <= 0)
		return std::string("");

	char* pszDst = new char[nLen];
	if (NULL == pszDst)
		return string("");

	WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL);
	pszDst[nLen - 1] = 0;
	std::string strTmp(pszDst);
	delete[] pszDst;
	return strTmp;
}

//获取当前系统的所有进程PID
vector<ProcessInfo> GetProcessInfo()
{
	STARTUPINFO st;
	PROCESS_INFORMATION pi;
	PROCESSENTRY32 ps;
	HANDLE hSnapshot;
	vector<ProcessInfo> PInfo;

	ZeroMemory(&st, sizeof(STARTUPINFO));
	ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
	st.cb = sizeof(STARTUPINFO);
	ZeroMemory(&ps, sizeof(PROCESSENTRY32));
	ps.dwSize = sizeof(PROCESSENTRY32);
	//拍摄进程快照
	hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnapshot == INVALID_HANDLE_VALUE)
	{		
		return PInfo;//快照拍摄失败
	}

	if (!Process32First(hSnapshot, &ps))
	{
		return PInfo;
	}

	//将进程PID、进程名称存到容器Vector中
	do
	{
		PInfo.emplace_back(ps.th32ProcessID, WCHAR2String(ps.szExeFile));

	} while (Process32Next(hSnapshot, &ps));

	//关闭快照句柄
	CloseHandle(hSnapshot);

	//排序
	sort(PInfo.begin(), PInfo.end());

	return PInfo;
}

int main(int argc, char* argv[])
{
	vector<ProcessInfo> PInfo = GetProcessInfo();

	if (PInfo.size())
	{
		cout << "编号\t进程对应id(十进制)" << endl;
		for (vector<DWORD>::size_type iter = 0; iter < PInfo.size(); iter++)
		{
			
			//if (PInfo[iter].PID == 4036) { //这里可以通过进程ID或者名称判断,比如切换进程和发送指令等等
				cout << iter << "\t\t" << dec << PInfo[iter].PID << "\t" << PInfo[iter].PName.c_str() << endl;
			//}
		}
	}
	return 0;
}

关于作者

清心醉 administrator

发表评论

请输入验证码: