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

Drawing a Focus Rectangle Around the Active Control

By Zarko Gajic, About.com

The Generic Solution to Coloring the Focused Entry Control article showed how to provide visually more attractive user-friendly interfaces for your Delphi applications by changing the background color of the currently selected control - the control that has the input focus.

To create event more eye-catching effect you could "draw" a rectange around the focused control.

Delphi's TShape control is the perfect candidate for the job, it represents a geometric shape that can be drawn on a form.
Every time the focus ships to another input control, you "move" the Shape control "over" the active control.

In the Form's OnCreate event a Shape is created:

   focusRectangle := TShape.Create(self) ;

   focusRectangle.Shape := stRectangle;

   focusRectangle.Visible := false;

   focusRectangle.Brush.Style := bsClear;
   focusRectangle.Pen.Style := psDot;
   focusRectangle.Pen.Color := clRed;
   focusRectangle.Pen.Width := 1;
Note: the focusRectangle is a varibale of type TShape defined in the interface-private section of the form declaration.

Now, each time the input focus ships from a control to another, we ship the focusRectangle also.

Use the ScreenActiveControlChange procedure from the Coloring Focused Control article. The ScreenActiveControlChange handles the OnActiveControlChange event of the global Screen object.

with focusRectangle do
begin
   Parent := Screen.ActiveControl.Parent;

   Top := Screen.ActiveControl.Top - 2;
   Height := Screen.ActiveControl.Height + 4;
   Left := Screen.ActiveControl.Left - 2;
   Width := Screen.ActiveControl.Width + 4;

   Visible := true;
  end;
The focusRectangle's Parent property is changed to match the Parent of the active control. The Top, Left, Width and Height properties are also changed for the Shape object to "fit" around the focused control.

Delphi tips navigator:
» Add you Delphi application to the Windows "Send To" menu
« How to Detach an Event Handler from a Control Event

More Delphi Programming Quick Tips
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. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. Drawing a Focus Rectangle Around the Active Control in Delphi Applications

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

All rights reserved.