1. Home
  2. Computing & Technology
  3. Delphi Programming

Get the Active (Focused) Control Outside of your Delphi application

By Zarko Gajic, About.com

When a user is working within your application, to grab the (handle of the) active control - the one with the input focus, you can simply use Delphi's "Screen.ActiveControl" property.

Screen's ActiveControl indicates which windowed control object in the active form currently receives the input from the keyboard.

If you have, for example, a system tray Delphi application and you need to know, on the global level, which control outside of your application has the input focus, you need to think out of the box.

Let's say you need to display something like a hint window below the currently active control - you would need to know the bounding rectangle (TRect) of this control that is not inside your application.

Get Focused Control's Rectangle

The GetFocusedControlRect returns the bounding rectangle of the currently active window (control) in the application that has the input focus - the one the user is currently operating on.

//get the rectangle of the active control (outside of the application)
function GetFocusedControlRect: TRect;
var
  focusedHandle, activeWinHandle: HWND;
  focusedRect: TRect;
  focusedThreadID : DWORD;
begin
  activeWinHandle := GetForegroundWindow;
  focusedThreadID := GetWindowThreadProcessID(activeWinHandle, nil) ;
  if AttachThreadInput(GetCurrentThreadID, focusedThreadID, true) then
  try
    focusedHandle := GetFocus;
    if focusedHandle <> 0 then
    begin
      GetWindowRect(focusedHandle, focusedRect) ;
      result := focusedRect;
    end
    else

      result := rect(0, 0, Screen.width, Screen.height) ;
  finally
    AttachThreadInput(GetCurrentThreadID, focusedThreadID, false) ;
  end;
end;
Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Advanced Delphi Techniques
  5. Get the Active (Focused) Control Outside of your Delphi application

©2009 About.com, a part of The New York Times Company.

All rights reserved.