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

进程篇----获取线程ID(By ProcessName) CreateToolhelp32Snapshot

程序员文章站 2022-07-05 11:51:08
...

通过ToolHelper中的API函数 CreateToolhelp32Snapshot来获取目标进程中的线程ID。

 

	BOOL GetThreadIdentify(HANDLE ProcessIdentify, vector<HANDLE>& ThreadIdentify)
	{

		BOOL IsOk = FALSE;
		HANDLE SnapshotHandle = INVALID_HANDLE_VALUE;
		THREADENTRY32	ThreadEntry32 = { 0 };
		ThreadEntry32.dwSize = sizeof(THREADENTRY32);
		int LastError = 0;

		if (IsBadReadPtr(&ProcessIdentify, sizeof(HANDLE)))
		{

			LastError = ERROR_INVALID_PARAMETER;
			goto Exit;
		}

		SnapshotHandle = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
		if (SnapshotHandle == INVALID_HANDLE_VALUE)
		{
			LastError = GetLastError();
			goto Exit;
		}
		if (!Thread32First(SnapshotHandle, &ThreadEntry32))
		{

			LastError = GetLastError();
			goto Exit;
		}

		do
		{
			if (ThreadEntry32.th32OwnerProcessID == (DWORD)ProcessIdentify)
			{

				ThreadIdentify.emplace_back((HANDLE)ThreadEntry32.th32ThreadID);
				IsOk = TRUE;
			}

		} while (Thread32Next(SnapshotHandle, &ThreadEntry32));


	Exit:

		if (SnapshotHandle != INVALID_HANDLE_VALUE)
		{
			CloseHandle(SnapshotHandle);
		}
		SnapshotHandle = INVALID_HANDLE_VALUE;
		SetLastError(LastError);
		return IsOk;
	}

 

相关标签: 代码积累记录