Get handle of focused control from another applications window

c, c++, delphi, windows

Solution

See remarks section in `GetFocus`' documentation for an explanation of the below example.

function GetFocus: HWND;
var
  Wnd: HWND;
  TId, PId: DWORD;
begin
  Result := windows.GetFocus;
  if Result = 0 then begin
    Wnd := GetForegroundWindow;
    if Wnd <> 0 then begin
      TId := GetWindowThreadProcessId(Wnd, PId);
      if AttachThreadInput(GetCurrentThreadId, TId, True) then begin
        Result := windows.GetFocus;
        AttachThreadInput(GetCurrentThreadId, TId, False);
      end;
    end;
  end;
end;

Problem

I have an application has window this some controls (buttons, edits etc). I need to simulate user event (Like Tab click and input text). I'm using `keybd_event` to move focus between tab ordered controls (editboxes) and input text to them. But I need to know handle of current focused control (for example for get text from it or change its styles). How can I solve it? ps I'm writing Delphi now but it does not matter (Win-API everywhere the same).

Original source