c++windowsmultithreadingdll-injection

Getting a handle to the process's main thread


I have created an additional thread in some small testing app and want to suspend the main thread from this additional thread. The additional thread is created via CreateRemoteThread from an external process.

Since SuspendThread needs a HANDLE to the thread which should be suspended, I want to know how to get this HANDLE from code running in my additional thread.


Solution

  • DWORD GetMainThreadId () {
        const std::tr1::shared_ptr<void> hThreadSnapshot(
            CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0), CloseHandle);
        if (hThreadSnapshot.get() == INVALID_HANDLE_VALUE) {
            throw std::runtime_error("GetMainThreadId failed");
        }
        THREADENTRY32 tEntry;
        tEntry.dwSize = sizeof(THREADENTRY32);
        DWORD result = 0;
        DWORD currentPID = GetCurrentProcessId();
        for (BOOL success = Thread32First(hThreadSnapshot.get(), &tEntry);
            !result && success && GetLastError() != ERROR_NO_MORE_FILES;
            success = Thread32Next(hThreadSnapshot.get(), &tEntry))
        {
            if (tEntry.th32OwnerProcessID == currentPID) {
                result = tEntry.th32ThreadID;
            }
        }
        return result;
    }