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

How to find what control was previously selected

By , 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?

Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. TEdit, TMaskEdit
  6. How to find what control was previously selected

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

All rights reserved.