方法一:
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
PROCESSENTRY32 process = {sizeof(PROCESSENTRY32)};
while (Process32Next(hProcessSnap,&process)){
cout << process.szExeFile << endl;
}
效果图:
方法二:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <tlhelp32.h>
#include <WtsApi32.h>
#pragma comment(lib,"WtsApi32.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// 初始化
DWORD dwCount = 0;
PWTS_PROCESS_INFO pi = { 0 };
if(WTSEnumerateProcesses(
NULL, // 会话主机服务器句柄,NULL:本地主机
0, // 保留(必须是 0)
1, // 保留(必须是 1)
&pi, // 接收 WTS_PROCESS_INFO 对象的指针
&dwCount // 接收 WTS_PROCESS_INFO 对象的数量
)){
// 遍历进程
for(int i = 0; i < dwCount; i++){
cout << "pProcessName:" << pi[i].pProcessName << endl;
cout << "ProcessId:" << pi[i].ProcessId << endl;
cout << "pUserSid:" << pi[i].pUserSid << endl;
cout << "SessionId:" << pi[i].SessionId << endl;
cout << "----------------------" << endl;
}
}
getchar();
return 0;
}
效果图:
方法三:
这种方法和第一个没有什么区别,只是将 while 用 for 来代替,看起来更加清晰。
// 创建进程快照
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (INVALID_HANDLE_VALUE == hProcessSnap){cout << "CreateToolhelp32Snapshot failed." << endl;}
// 遍历进程
PROCESSENTRY32 process = {sizeof(PROCESSENTRY32)};
for(BOOL flag = Process32First(hProcessSnap,&process);flag;flag = Process32Next(hProcessSnap,&process)){
// do something
// ...
// ...
}