1. Computing

How to find what control was previously selected

From , former About.com Guide

Suppose you have two Edit (Edit1 and Edit2) boxes on a Form (Form1). Suppose you need to know what Edit box had the input focus (was selected) when you click a button (Button1).

Here's how to find out what control was the last one with the input focus...

Delphi's TScreen object has an event called OnActiveControlChange, which fires immediately after input focus changes to a new windowed control.

~~~~~~~~~~~~~~~~~~~~~~~~~
//Add a new public procedure, ActiveControlChanged,
//to the TForm1 class declaration,
//and two private TWinControl type variables

private
   wcActive, wcPrevious : TWinControl;
public
   procedure ActiveControlChanged(Sender: TObject) ;

...

procedure TForm1.FormCreate(Sender: TObject) ;
begin
   Screen.OnActiveControlChange := ActiveControlChanged;
end;

procedure TForm1.ActiveControlChanged(Sender: TObject) ;
begin
    wcPrevious := wcActive;
    wcActive := Form1.ActiveControl;
end;

procedure TForm1.FormDestroy(Sender: TObject) ;
begin
   Screen.OnActiveControlChange := nil;
end;

procedure TForm1.Button1Click(Sender: TObject) ;
begin
   if TEdit(wcPrevious) = Edit1 then
     ShowMessage('Edit1 had focus')
   else if TEdit(wcPrevious) = Edit2 then
     ShowMessage('Edit2 had focus')
   else
     ShowMessage('Some other control had a focus!') ;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» How to determine the output of a console application
« What is being typed into the DBGrid?

©2013 About.com. All rights reserved.