admin 管理员组

文章数量: 887016

//-----------------------------------------------------------------------------
// 程序说明:获取系统中当前所有进程PID、进程名称
//
//-----------------------------------------------------------------------------

#include<Windows.h>
#include<iostream>
#include<TlHelp32.h>
#include<vector>
#include<algorithm>

using namespace std;

//定义结构:进程PID、进程名称
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++)
		{
			cout << iter << "\t\t" << dec << PInfo[iter].PID << "\t" << PInfo[iter].PName.c_str() << endl;
		}
	}
	else
	{
		cout << "未找到进程" << endl;
	}

	return 0;
}

 

本文标签: 进程 操作系统 名称 代码 Windows