1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
|
#include <psapi.h>
#define MAX_PROCESSES 1024
DWORD FindProcess(__in_z LPCTSTR lpcszFileName)
{
LPDWORD lpdwProcessIds;
LPTSTR lpszBaseName;
HANDLE hProcess;
DWORD i, cdwProcesses, dwProcessId = 0;
lpdwProcessIds = (LPDWORD)HeapAlloc(GetProcessHeap(), 0, MAX_PROCESSES*sizeof(DWORD));
if (lpdwProcessIds != NULL)
{
if (EnumProcesses(lpdwProcessIds, MAX_PROCESSES*sizeof(DWORD), &cdwProcesses))
{
lpszBaseName = (LPTSTR)HeapAlloc(GetProcessHeap(), 0, MAX_PATH*sizeof(TCHAR));
if (lpszBaseName != NULL)
{
cdwProcesses /= sizeof(DWORD);
for (i = 0; i < cdwProcesses; i++)
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, lpdwProcessIds[i]);
if (hProcess != NULL)
{
if (GetModuleBaseName(hProcess, NULL, lpszBaseName, MAX_PATH) > 0)
{
if (!lstrcmpi(lpszBaseName, lpcszFileName))
{
dwProcessId = lpdwProcessIds[i];
CloseHandle(hProcess);
break;
}
}
CloseHandle(hProcess);
}
}
HeapFree(GetProcessHeap(), 0, (LPVOID)lpszBaseName);
}
}
HeapFree(GetProcessHeap(), 0, (LPVOID)lpdwProcessIds);
}
return dwProcessId;
}
|