Skip to content

Instantly share code, notes, and snippets.

@pps83
Created February 15, 2018 21:31
Show Gist options
  • Save pps83/7ebd398174ddd50987df2d6602da1629 to your computer and use it in GitHub Desktop.
Save pps83/7ebd398174ddd50987df2d6602da1629 to your computer and use it in GitHub Desktop.
suspend threads in the current process
#include <windows.h>
#include <tlhelp32.h>
// Pass 0 as the targetProcessId to suspend threads in the current process
void DoSuspendThread(DWORD targetProcessId, DWORD targetThreadId)
{
HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
if (h != INVALID_HANDLE_VALUE)
{
THREADENTRY32 te;
te.dwSize = sizeof(te);
if (Thread32First(h, &te))
{
do
{
if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID))
{
// Suspend all threads EXCEPT the one we want to keep running
if (te.th32ThreadID != targetThreadId && te.th32OwnerProcessID == targetProcessId)
{
HANDLE thread = ::OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID);
if (thread != NULL)
{
SuspendThread(thread);
CloseHandle(thread);
}
}
}
te.dwSize = sizeof(te);
}
while (Thread32Next(h, &te));
}
CloseHandle(h);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment