psapi.dll枚举进程

使用 psapi.dll 中的函数 枚举系统正在运行的进程

用到的函数

BOOL WINAPI EnumProcesses(
  _Out_  DWORD *pProcessIds,
  _In_   DWORD cb,
  _Out_  DWORD *pBytesReturned
);
BOOL WINAPI EnumProcessModules(
  _In_   HANDLE hProcess,
  _Out_  HMODULE *lphModule,
  _In_   DWORD cb,
  _Out_  LPDWORD lpcbNeeded
);
DWORD WINAPI GetModuleFileNameEx(
  _In_      HANDLE hProcess,
  _In_opt_  HMODULE hModule,
  _Out_     LPTSTR lpFilename,
  _In_      DWORD nSize
);

代码示例

#include <Windows.h>
#include <stdio.h>
#include <psapi.h>
#define TOTAL 1024
//提升进程权限
BOOL UpdateProcessPrivilege(HANDLE hProcess, LPCTSTR lpPrivilegeName = SE_DEBUG_NAME);
// hProcess [in] : 要提升的进程,目标进程
// lpPrivilegeName [in] : 要提升到的特权,目标特权
// 返回值 : TRUE : 成功; FALSE : 失败


int main(int argv,char*argc[]) {

    UpdateProcessPrivilege(GetCurrentProcess());//提升当前进程权限

	DWORD aProcesses[TOTAL];
	DWORD lpcbNeed;
	DWORD cProcesses;
	if (!EnumProcesses(aProcesses, TOTAL, &lpcbNeed))
	{
		 printf("EnumProcesses error\n");
		 return -1;
	}
	//计算返回了多少进程标识符
	cProcesses = lpcbNeed / sizeof(DWORD);

	printf("一共有%d个进程\n",cProcesses);
	for (DWORD i = 0; i < cProcesses; i++)
	{	
		//printf("进程ID %d\n", aProcesses[i]);
		
		HANDLE  proHandle = OpenProcess(PROCESS_QUERY_INFORMATION| PROCESS_VM_READ, FALSE, aProcesses[i]);
		//打开进程
		if (NULL != proHandle) {
	
			TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

			printf("进程打开成功%d\n", aProcesses[i]);

			HMODULE hMod[TOTAL];
			DWORD cNedded;
			//枚举进程模块
			if (EnumProcessModules(proHandle,hMod, sizeof(hMod), &cNedded))
			{
				for (int j = 0; j < cNedded/sizeof(HMODULE); j++)
				{
					 TCHAR szModName[MAX_PATH];
					 if (GetModuleFileNameEx(proHandle, hMod[j], szModName,sizeof(szModName) / sizeof(TCHAR)))
					 {
						  //printf("\n%d %s (0x%08x)\t",j,szModName, hMod[j]);
						 printf("%d %ls %x\n",j,szModName,hMod[j]);
					 }
				}
			}
			CloseHandle(proHandle);

		}
		else {
			 printf("进程打开失败%d 错误代码: %d\n", aProcesses[i],GetLastError());
		}
	}

	getchar();
}

BOOL UpdateProcessPrivilege(HANDLE hProcess, LPCTSTR lpPrivilegeName)
{
	HANDLE hToken;
	if (::OpenProcessToken(hProcess, TOKEN_ALL_ACCESS, &hToken)) {

		LUID destLuid;
		if (::LookupPrivilegeValue(NULL, lpPrivilegeName, &destLuid)) {

			TOKEN_PRIVILEGES TokenPrivileges;
			TokenPrivileges.PrivilegeCount = 1;
			TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
			TokenPrivileges.Privileges[0].Luid = destLuid;
			int iResult;
			if (iResult = ::AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges,
				0, NULL, NULL)) {

				return TRUE;
			}
		}
	}

	return FALSE;
}
本博客所有文章如无特别注明均为原创。作者:odaycaogen复制或转载请以超链接形式注明转自 123``blog
原文地址《psapi.dll枚举进程

相关推荐

发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(0)