欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

进程篇----获取进程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;

 

}

 

相关标签: 代码积累记录