title: Delphi: Simulate key press for automation
body: <p>I want to change text of an edit control of an external application. The application is written in Delphi. It has several forms. I started with Python libraries <code>pywinauto</code> + <code>sendkeys</code> to test the first form <code>TLoginForm</code>. It works perfectly. Here is the pseudo code:</p>
  
  <pre><code>helper = pywinauto.application.Application()
  hwnd = pywinauto.findwindows.find_windows(class_name='TLoginForm')[0]
  window = helper.window_(handle=hwnd)
  ctrl = window[2]   # the second control is the edit control I want to access
  ctrl.ClickInput()  # focus the control
  ctrl.SetEditText('Hello world')  # text can be changed expectedly
  </code></pre>
  
  <p>As the second step, I want make an UI for the automation tool. But due to lack knowledge of Python UI and considering of the complexity to distribute binary in Python, I want to do it Delphi. But the weird thing is I am not able to read/write the edit control in Delphi by using Windows apis. Here are some attempts:</p>
  
  <pre class="lang-pascal prettyprint-override"><code>SetForegroundWindow(EditControlHandle); // Works, the application will be brought to front, the edit control will be focused
  
  // Attempt 1: Nothing happens
  SetFocus(AnotherEditControlHandle);
  
  // Attempt 2: Nothing happens
  SetWindowText(EditControlHandle, 'Hello world');
  
  // Attempt 3: Nothing happens
  SendKeys32.SendKey('Hello world', {Wait=}True); 
  
  // Attempt 4: Nothing happens
  SendMessage(EditControlHandle, Ord('H'), WM_KEYDOWN, 0);
  SendMessage(EditControlHandle, Ord('H'), WM_KEYUP, 0);
  
  // Attempt 5: AttachThreadInput will return False, the reason is "Access Denied"
  FocusedThreadID := GetWindowThreadProcessID(ExternalAppMainWindowHandle, nil);
  if AttachThreadInput(GetCurrentThreadID, FocusedThreadID, {Attach=}True) then
  </code></pre>
  
  <p>As it works in Python, I think I must have missed something very basic and very important. But I am now so blind to find the problem. Any hints are very much appreciated.</p>