title: Determining main thread id of extern process (ReadProcessMemory - Err 299)
body: <p>I tried to get the main thread id of a another process, like it was suggested here:</p>
  
  <p><a href="https://stackoverflow.com/a/8058710/1386873">https://stackoverflow.com/a/8058710/1386873</a></p>
  
  <pre><code>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)&amp;dwTid, sizeof(int), NULL) == FALSE)
      {
          CloseHandle(hProcess);
          return NULL;
      }
  
      CloseHandle(hProcess);
  
      return (DWORD)dwTid;
  }
  </code></pre>
  
  <p>But this does not work: <code>ReadProcessMemory</code> always returns a 299 Code from <code>GetLastError()</code>, 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? <code>BytesRead</code> are also always 0. 
  I get the process id like this:</p>
  
  <pre><code>unsigned long GetTargetProcessIdFromWindow(LPCWSTR className, LPCWSTR windowName)
  {
      unsigned long processID = 0;
      HWND targetWnd;
  
      targetWnd = FindWindow(className, windowName);
      GetWindowThreadProcessId(targetWnd, &amp;processID);
  
      return processID;
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>Thanks for any tips.</p>