C++枚举进程的方法

来源:互联网 发布:java 0xff 编辑:程序博客网 时间:2024/06/02 08:11

主要使用的下面几个函数:

1、CreateToolhelp32Snapshot

2、Process32First

3、Process32Next

所以要引用下面的头文件:

#include <tlhelp32.h>


枚举进程的代码如下:

// 枚举系统当前所有进程信息// 并把信息输出到工程目录下EnumInfo_ToolHelp_process.txtBOOL EnumProcessInfo(){// 定义进程信息结构PROCESSENTRY32 pe32 = {sizeof(pe32)} ;// 创建系统当前进程快照HANDLE hProcessShot = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS, 0 ) ;if ( hProcessShot == INVALID_HANDLE_VALUE )return FALSE ;// 输出进程信息到文件ofstream fout ( "EnumInfo_ToolHelp_process.txt" ) ;// 循环枚举进程信息char szBuf[MAX_BUF_SIZE] = {0} ;if ( Process32First ( hProcessShot, &pe32 ) ){do {memset ( szBuf, 0, sizeof(szBuf) ) ;// 把宽字符的进程名转化为ANSI字符串WideCharToMultiByte (CP_ACP, 0, pe32.szExeFile, wcslen(pe32.szExeFile), szBuf, sizeof(szBuf), NULL, NULL );fout << "Process: " << szBuf << endl ;fout << '\t' << "Usage           : " << pe32.cntUsage << endl ;fout << '\t' << "ProcessID       : " << pe32.th32ProcessID << endl ;fout << '\t' <<"DefaultHeapID   : " << (ULONG_PTR)pe32.th32DefaultHeapID << endl ;fout << '\t' << "ModuleID        : " << pe32.th32ModuleID << endl ;fout << '\t' << "ThreadNum       : " << pe32.cntThreads<< endl ;fout << '\t' << "ParentProcessID : " << pe32.th32ParentProcessID << endl ;fout << '\t' << "PriClassBase    : " << pe32.pcPriClassBase << endl ;}while ( Process32Next ( hProcessShot, &pe32 ) ) ;}fout.close () ;CloseHandle ( hProcessShot ) ;return TRUE ;}