Thursday, October 25, 2007

Implementing "Contains Focus" for Delphi's Container Controls: TPanel, TGroupBox

In complex form designs where you have dozens of controls contained in several containers it is sometimes necessary to find out whether the focused control (the one with the input focus) is a child of some overall parent of a group of controls.

Picture the next design: you are using frame objects to group controls together (or any other type of container control). You are dynamically instatiating the frame object(s) to be arranged on the form at run-time.

At some point in the life of the application you need to figure out if a specific frame has the input focus - or better to say - if the frame contains the control with the input focus.

TWinControl.Contains Focus?

The ContainsFocus focus function returns true if the control, or one of its child controls, currently has the input focus.
function ContainsFocus(control : TWinControl) : boolean;
. focusedHandle : HWND;
. focusedControl : TWinControl;
. focusedHandle := Windows.GetFocus() ;

. focusedControl := FindControl(focusedHandle) ;

. if focusedControl = nil then
. result := false
. else
. begin

. result := control.ContainsControl(focusedControl) ;
. end;
Let's say you have a few Edit boxes inside a Panel inside a GroupBox (GroupBox1).

If you need to figure out whether the GroupBox contains the control with the input focus (active control) you can call the ContainsFocus, as in:

if ContainsFocus(GroupBox1) then
// read from all edit boxes and
// store the values somewhere


No comments: