Mega Code Archive

 
Categories / Delphi / Examples
 

Get caption and class of active window in active [other] process

Question: How can I find the active child window (like the 'follow focus' option in WinSight). I know how to enumerate child windows, but I don't know how to detect if a child window is active (has the caret / focus). Answer: Use the procedure below. It will return the handle, class name and caption text through 3 var parameters. procedure GetFocusedControl(var FocusWin: HWND; var ClassName, ControlText: string); var hOtherWin: HWND; OtherThreadID: Cardinal; aDwordvar: DWORD; hFocusWin: HWND; S, ss: string; I: Integer; begin S := ''; ss := ''; hFocusWin := -1; hOtherWin := GetForegroundWindow; OtherThreadID := GetWindowThreadProcessID(hOtherWin, @aDwordvar); if AttachThreadInput(GetCurrentThreadID, OtherThreadID, True) then begin hFocusWin := GetFocus; if hFocusWin<>0 then try I := SendMessage(hFocusWin, WM_GETTEXTLENGTH, 0, 0); SetLength(S, I+1); SendMessage(hFocusWin, WM_GETTEXT, I+1, Integer(PChar(S))); SetLength(ss, 260); GetClassName(hFocusWin, PChar(ss), 260); finally AttachThreadInput(GetCurrentThreadID, OtherThreadID, False); end; end; FocusWin := hFocusWin; ClassName := Trim(ss); ControlText := Trim(S); end;