#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "psapi.h"
//添加连接库
#pragma comment(lib,"psapi.lib")
void PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE,
processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
// 枚举进程模块信息
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )
{
//GetModleFileName返回进程名包含路径
//GetModuleBaseName返回进程名不包含路径
//通过进程句柄 获取进程名 // 取得主模块全名,每个进程的第一模块
即为进程主模块
GetModuleBaseName( hProcess, hMod, szProcessName, sizeof
(szProcessName)/sizeof(TCHAR) );
}
}
// Print the process name and identifier.
_tprintf( TEXT("%s (PID: %u)\n"), szProcessName, processID );
CloseHandle( hProcess );
}
void main( )
{
// Get the list of process identifiers.
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
return;
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
if( aProcesses[i] != 0 )
PrintProcessNameAndID(aProcesses[i]);
}