新"该答案引用chatGPT"
请参考下面的代码,还请测试:
#include <Windows.h>
#include <winternl.h>
#include <tchar.h>
typedef NTSTATUS(NTAPI *_PsLookupProcessByProcessId)(
HANDLE ProcessId,
PEPROCESS *Process
);
typedef NTSTATUS(NTAPI *_PsGetProcessImageFileName)(
PEPROCESS Process,
PUNICODE_STRING ImageFileName
);
void findPidByName(const WCHAR* processName)
{
_PsLookupProcessByProcessId PsLookupProcessByProcessId = (_PsLookupProcessByProcessId)GetProcAddress(
GetModuleHandle(L"ntdll.dll"), "PsLookupProcessByProcessId");
_PsGetProcessImageFileName PsGetProcessImageFileName = (_PsGetProcessImageFileName)GetProcAddress(
GetModuleHandle(L"ntdll.dll"), "PsGetProcessImageFileName");
PEPROCESS pProcess = NULL;
HANDLE hProcess = NULL;
DWORD aProcesses[1024], cbNeeded, cProcesses;
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
{
return;
}
cProcesses = cbNeeded / sizeof(DWORD);
for (unsigned int i = 0; i < cProcesses; i++)
{
if (aProcesses[i] != 0)
{
if (NT_SUCCESS(PsLookupProcessByProcessId((HANDLE)aProcesses[i], &pProcess)))
{
UNICODE_STRING ImageFileName;
if (NT_SUCCESS(PsGetProcessImageFileName(pProcess, &ImageFileName)))
{
WCHAR processImageName[MAX_PATH];
wcsncpy_s(processImageName, ImageFileName.Buffer, ImageFileName.Length / sizeof(WCHAR));
processImageName[ImageFileName.Length / sizeof(WCHAR)] = '\0';
if (wcscmp(processImageName, processName) == 0)
{
wprintf(L"Found process with name '%s' and PID %d\n", processImageName, aProcesses[i]);
break;
}
}
}
}
}
}