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;
}
版权声明:本文标题:【C++】代码实现:获取 Windows 操作系统当前所有进程PID、进程名称 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/jishu/1729012459h1306795.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论