用EnumProcesses()枚举进程

参照msdn的例子,用EnumProcesses()枚举进程并输入进程名和句柄。以下代码在vs2008中测试通过:

#include "stdafx.h"
#include <windows.h>
#include "psapi.h"
#pragma   comment   (lib, "psapi.lib ")

  
void MyEnumProcess()
{
	// Get the list of process identifiers.
	DWORD aProcesses[1024], cbNeeded, cProcesses;
	unsigned int i;

	if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )       //枚举进程
		return;
	cProcesses = cbNeeded / sizeof(DWORD);             //计算进程个数
	for ( i = 0; i < cProcesses; i++ )
		if( aProcesses[i] != 0 )
		{

			TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
			HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |PROCESS_VM_READ,FALSE, aProcesses[i] );     //获得进程句柄

			if (NULL != hProcess )
			{
				HMODULE hMod;
				DWORD cbNeeded;

				if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod), &cbNeeded) )        //枚举进程模块信息
				{
					GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR) );       //取得主模块全名,每个进程第一模块则为进程主模块
				}
			}
			_tprintf( TEXT("%s  (PID: %u)\n"), szProcessName, aProcesses[i] );     //输出进程名及PID
			CloseHandle( hProcess );
		}
}


void main( )
{
    MyEnumProcess();
	system("pause");
}
代码在我电脑上的运行结果如下图:

用EnumProcesses()枚举进程_第1张图片


你可能感兴趣的:(list,测试,null,System,query,Path)