#include <Windows.h>
#include <stdio.h>
#include <tlhelp32.h>
//默认线程栈大小1M,32位系统进程可用空间为2G
//所以一个进程最多有2G/1M=2048个线程
#define MAXTHREADCOUNT 2048
void ListAllThreadInProc(DWORD *pdwThread, const DWORD dwProcId)
{
int i = 0;
HANDLE snapshot;
THREADENTRY32 threadinfo = {0};
BOOL status;
snapshot=CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (snapshot==INVALID_HANDLE_VALUE)
return;
threadinfo.dwSize = sizeof(THREADENTRY32);
status= Thread32First(snapshot,&threadinfo);
while (status)
{
if (i >= MAXTHREADCOUNT)
return;
if (threadinfo.th32OwnerProcessID == dwProcId)
{
pdwThread[i] = threadinfo.th32ThreadID;
printf("[%d]%u/n", i, pdwThread[i]);
i++;
}
status=Thread32Next(snapshot,&threadinfo);
}
return;
}
DWORD FindTargetProcess(LPCSTR pszProcName)
{
HANDLE snapshot;
PROCESSENTRY32 processinfo;
DWORD dwTargetProcId = 0;
//进程快照
snapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
if(snapshot==INVALID_HANDLE_VALUE)
return 0;
//通过遍历进程取得进程名为pszProcName的进程ID
processinfo.dwSize=sizeof(processinfo);
BOOL status= Process32First(snapshot,&processinfo);
while(status)
{
if(lstrcmpi(pszProcName, processinfo.szExeFile)==0)
{
dwTargetProcId = processinfo.th32ProcessID;
break;
}
status=Process32Next(snapshot,&processinfo);
}
CloseHandle(snapshot);
return dwTargetProcId;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("请将进程名作为参数!/n");
return -1;
}
DWORD dwProcId = FindTargetProcess(argv[1]);
if (0 == dwProcId)
{
printf("未找到指定进程:%s!/n", argv[1]);
return -1;
}
DWORD dwTargetIndex = 0;
printf("选择线程ID:/n");
DWORD dwThreadId[MAXTHREADCOUNT] = {0};
ListAllThreadInProc(dwThreadId, dwProcId);
scanf_s("%u", &dwTargetIndex, sizeof(dwTargetIndex));
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, dwThreadId[dwTargetIndex]);
if (NULL == hThread)
{
printf("OpenThread failed! Error code is 0x%08x!/n", GetLastError());
return -1;
}
SuspendThread(hThread);
CONTEXT ct = {0};
ct.ContextFlags = CONTEXT_CONTROL;
GetThreadContext(hThread, &ct);
return 0;
}