C++ 根据程序名称获取线程ID
时间: 2024-03-10 17:45:12 浏览: 147
在 C++ 中,可以使用 Windows API 函数 `GetThreadId()` 来根据程序名称获取线程 ID。具体步骤如下:
1. 使用 `CreateToolhelp32Snapshot()` 函数创建进程快照,获取当前正在运行的所有进程信息。
2. 遍历进程快照,根据进程名称获取进程 ID。
3. 使用 `OpenProcess()` 函数打开进程,获取进程句柄。
4. 使用 `CreateToolhelp32Snapshot()` 函数创建线程快照,获取当前进程中所有线程信息。
5. 遍历线程快照,根据进程 ID 和线程名称获取线程 ID。
6. 关闭进程和线程快照句柄,释放资源。
以下是示例代码:
```c++
#include <windows.h>
#include <tlhelp32.h>
#include <iostream>
DWORD GetThreadIdByProcessNameAndThreadName(const std::wstring& processName, const std::wstring& threadName)
{
// 创建进程快照
HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnapshot == INVALID_HANDLE_VALUE)
{
std::cerr << "CreateToolhelp32Snapshot failed" << std::endl;
return 0;
}
DWORD processId = 0;
// 遍历进程快照,获取进程 ID
PROCESSENTRY32 processEntry = {};
processEntry.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hProcessSnapshot, &processEntry))
{
do
{
if (processName.compare(processEntry.szExeFile) == 0)
{
processId = processEntry.th32ProcessID;
break;
}
} while (Process32Next(hProcessSnapshot, &processEntry));
}
// 关闭进程快照句柄
CloseHandle(hProcessSnapshot);
if (processId == 0)
{
std::cerr << "Process not found: " << processName << std::endl;
return 0;
}
// 打开进程,获取句柄
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if (hProcess == NULL)
{
std::cerr << "OpenProcess failed" << std::endl;
return 0;
}
DWORD threadId = 0;
// 创建线程快照
HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (hThreadSnapshot == INVALID_HANDLE_VALUE)
{
std::cerr << "CreateToolhelp32Snapshot failed" << std::endl;
return 0;
}
// 遍历线程快照,获取线程 ID
THREADENTRY32 threadEntry = {};
threadEntry.dwSize = sizeof(THREADENTRY32);
if (Thread32First(hThreadSnapshot, &threadEntry))
{
do
{
if (threadEntry.th32OwnerProcessID == processId)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, threadEntry.th32ThreadID);
if (hThread != NULL)
{
// 获取线程名称
WCHAR threadNameBuffer[MAX_PATH] = {};
DWORD threadNameLength = GetThreadDescription(hThread, threadNameBuffer, MAX_PATH);
if (threadNameLength > 0)
{
std::wstring threadNameActual(threadNameBuffer, threadNameLength);
// 比较线程名称
if (threadName.compare(threadNameActual) == 0)
{
threadId = threadEntry.th32ThreadID;
break;
}
}
CloseHandle(hThread);
}
}
} while (Thread32Next(hThreadSnapshot, &threadEntry));
}
// 关闭线程快照句柄
CloseHandle(hThreadSnapshot);
// 关闭进程句柄
CloseHandle(hProcess);
return threadId;
}
```
调用示例:
```c++
DWORD threadId = GetThreadIdByProcessNameAndThreadName(L"myprocess.exe", L"mythread");
if (threadId != 0)
{
std::cout << "Thread ID: " << threadId << std::endl;
}
```
阅读全文