0

I tried to get the main thread id of a another process, like it was suggested here:

https://stackoverflow.com/a/8058710/1386873

DWORD GetMainThreadId(DWORD dwPid)
{
    LPCVOID lpTid;
    _asm
    {
        mov eax, fs:[18h]
        add eax, 36
        mov lpTid, eax
    }

    HANDLE hProcess = OpenProcess(PROCESS_VM_READ, FALSE, dwPid);
    if (hProcess == NULL)
        return NULL;

    int dwTid = 0;
    if (ReadProcessMemory(hProcess, lpTid, (LPVOID)&dwTid, sizeof(int), NULL) == FALSE)
    {
        CloseHandle(hProcess);
        return NULL;
    }

    CloseHandle(hProcess);

    return (DWORD)dwTid;
}

But this does not work: ReadProcessMemory always returns a 299 Code from GetLastError(), which means "ERROR_PARTIAL_COPY - Only part of a ReadProcessMemory or WriteProcessMemory request was completed.". Well the error message is pretty clear, but why does this happen? BytesRead are also always 0. I get the process id like this:

unsigned long GetTargetProcessIdFromWindow(LPCWSTR className, LPCWSTR windowName)
{
    unsigned long processID = 0;
    HWND targetWnd;

    targetWnd = FindWindow(className, windowName);
    GetWindowThreadProcessId(targetWnd, &processID);

    return processID;
}

which seems to be working fine. What might cause this? I tried different applications (Calculator, Notepad etc.). My application is build for Win32, my operating system is Windows 64bit. Does this have to do with the TIB? As far as i understand it, as long as i build it for Win32 the way i do it should be fine, shouldn't it.

Thanks for any tips.

Community
  • 1
  • 1
puelo
  • 5,464
  • 2
  • 34
  • 62
  • 1
    Win32 is *not* fine, this code cannot work for 64-bit processes. They have their TEB at a completely different address, one you can never get to from a 32-bit process. Building as x64 isn't a fix either, now you lose the ability to read the TEB for a 32-bit process. – Hans Passant Aug 06 '14 at 12:02
  • @HansPassant Ya. After i wrote this i realized that Notepad.exe and Calculator.exe would probably be 64bit processes. But i also tried to use this with the 32-bit version of a program and it did not work. – puelo Aug 06 '14 at 12:08

1 Answers1

0

Consider Toolhlp functions instead - CreateToolhelp32Snapshot() and Thread32First().

Seva Alekseyev
  • 59,826
  • 25
  • 160
  • 281
  • Yeah. I used this for now. But as far as i understand it there is no easy way to determine the main thread of the other process, besides looking at the snapshot time. And even then it is not reliable, since the main thread could already been closed. It is enough for me to get the id of one random thread on the process, so this solution is fine. – puelo Aug 06 '14 at 13:05