进程篇----获取进程ID(By ProcessName)CreateToolhelp32Snapshot
程序员文章站
2022-07-05 11:46:26
...
通过ToolHelper中的API函数 CreateToolhelp32Snapshot来获取进程ID。
BOOL GetProcessIdByProcessImageName(HANDLE* ProcessID,
const TCHAR* ProcessImageName
)
{
BOOL IsOk = FALSE;
HANDLE SnapshotHandle = INVALID_HANDLE_VALUE;
PROCESSENTRY32 ProcessEntry32;
ProcessEntry32.dwSize = sizeof(PROCESSENTRY32);
int LastError = 0;
SnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
//TH32CS_SNAPPROCESS:Includes all processes in the system in the snapshot.To enumerate the processes,
if (SnapshotHandle == INVALID_HANDLE_VALUE)
{
LastError = GetLastError();
return FALSE;
}
if (!Process32First(SnapshotHandle, &ProcessEntry32))
{
LastError = GetLastError();
goto Exit;
}
do
{
if (_tcsicmp(ProcessEntry32.szExeFile, ProcessImageName) == 0)
{
*ProcessID = (HANDLE)ProcessEntry32.th32ProcessID;
IsOk = TRUE;
goto Exit;
}
} while (Process32NextW(SnapshotHandle, &ProcessEntry32));
Exit:
if (SnapshotHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(SnapshotHandle);
}
SnapshotHandle = INVALID_HANDLE_VALUE;
SetLastError(LastError);
return IsOk;
}
上一篇: 关于map和null的一些小故事