1. Computing

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

By

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;

©2014 About.com. All rights reserved.