title: Using SendMessage in python to set text in foreground window
body: <p>We have an old, legacy database that needs input from another system. SendInput method of data input into database forms is slow and unreliable, setting clipboard and then ^v is not reliable either (I have no idea why, but database interface is very old, early 2000s). After a lot of fiddling I discovered that using SendMessage to set text and then sending VK_RETURN is fast (much faster than SendInput/keybd_event) and reliable with our database. Now this code in plain C works:</p>
  
  <pre><code>    HWND fghwnd = GetForegroundWindow();
      DWORD threadId = GetWindowThreadProcessId(fghwnd, NULL);
      DWORD myId = GetCurrentThreadId();
      if (AttachThreadInput(myId, threadId, true)) {
          HWND ctrl = GetFocus();
          SendMessage(ctrl, WM_SETTEXT, 0, (LPARAM) sendbuf); // TESTING
          PostMessage(ctrl, WM_KEYDOWN, VK_RETURN, 0);
          PostMessage(ctrl, WM_KEYUP, VK_RETURN, 0);
          AttachThreadInput(myId, threadId, false);
      } else {
          printf("\nError: AttachThreadInput failure!\n");
      }
  </code></pre>
  
  <p>But this one in python does not:</p>
  
  <pre><code>    foregroundHwnd = win32gui.GetForegroundWindow()
      foregroundThreadID = win32process.GetWindowThreadProcessId(foregroundHwnd)[0]
      ourThreadID = win32api.GetCurrentThreadId()
      if foregroundThreadID != ourThreadID:
          win32process.AttachThreadInput(foregroundThreadID, ourThreadID, True)
          focus_whd = win32gui.GetFocus()
          win32gui.SendMessage(focus_whd, win32con.WM_SETTEXT, None, "test text")
          win32gui.PostMessage(focus_whd, win32con.WM_KEYDOWN, win32con.VK_RETURN, None)
          win32gui.PostMessage(focus_whd, win32con.WM_KEYUP, win32con.VK_RETURN, None)
          win32process.AttachThreadInput(foregroundThreadID, ourThreadID, False)
  </code></pre>
  
  <p>The trouble is, most of our new logic in python. I turned that C code into a small python module and it works, but as result now I've got dependency on Microsoft's huge compiler and a lot of fiddling with module building. I'd like to have a python-only solution.</p>
  
  <p>Any ideas why this python code does not work? These system calls look the same...</p>