C++ 根据程序名称获取线程ID
时间: 2024-03-10 08:45:00 浏览: 228
一个用c++编写的聊天程序客户端.rar_c++ 聊天程序
可以使用Windows API函数 `GetThreadId` 来根据线程句柄获取线程ID。获取线程句柄可以使用 Windows API 函数 `CreateToolhelp32Snapshot` 和 `Thread32First`、`Thread32Next` 函数遍历系统中所有线程快照,检查每个线程的进程ID和线程名是否匹配。若匹配,则即可获取该线程的句柄,再通过 `GetThreadId` 函数获取线程ID。以下是一个示例代码:
```c++
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
DWORD GetThreadIdByName(const std::wstring& name) {
DWORD threadId = 0;
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snapshot == INVALID_HANDLE_VALUE) {
return 0;
}
THREADENTRY32 threadEntry = { sizeof(THREADENTRY32) };
if (Thread32First(snapshot, &threadEntry)) {
do {
if (threadEntry.th32OwnerProcessID == GetCurrentProcessId()) {
HANDLE threadHandle = OpenThread(THREAD_QUERY_INFORMATION, FALSE, threadEntry.th32ThreadID);
if (threadHandle != nullptr) {
TCHAR moduleName[MAX_PATH] = { 0 };
GetModuleFileNameEx(threadHandle, nullptr, moduleName, MAX_PATH);
if (wcsstr(moduleName, name.c_str()) != nullptr) {
threadId = GetThreadId(threadHandle);
CloseHandle(threadHandle);
break;
}
CloseHandle(threadHandle);
}
}
} while (Thread32Next(snapshot, &threadEntry));
}
CloseHandle(snapshot);
return threadId;
}
```
调用示例:
```c++
DWORD threadId = GetThreadIdByName(L"myprogram.exe");
if (threadId != 0) {
// 获取到线程ID,可以执行相关操作
} else {
// 未找到指定名称的线程
}
```
阅读全文