OnActiveControlChange (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example uses the OnActiveControlChange event to detect when focus changes on the form. When focus changes, the hint for the active control is displayed on the status bar. To use this example, you must add a status bar to the form and set its SimplePanel property to True. Add a new public procedure, ActiveControlChanged, to the TForm1 class declaration.

Code

type
  TForm1 = class(TForm)
    StatusBar1, StatusBar2: TStatusBar;
    Button1: TButton;
    RadioButton1: TRadioButton;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure MouseOverChanged(Sender: TObject);
  private
    { Private declarations }
  public
    procedure ActiveControlChanged(Sender: TObject);
  end;

var
  Active : TWinControl;
  I: Integer;
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.ActiveControlChanged(Sender: TObject);
var
  Active : TWinControl;
  I: Integer;
begin
  Active := nil;
  for I:= 0 to ControlCount -1 do
  begin
    if (Controls[I] is TWinControl) then
      if (Controls[I] as TWinControl).Focused then
        Active := TWinControl(Controls[I]);
  end;
  if ((Active <> nil) and (Active.Hint <> '')) then
  begin
    StatusBar2.SimpleText := GetLongHint(Active.Hint) + ' focus';
  end
end;

procedure TForm1.MouseOverChanged(Sender: TObject);
var
  Active : TWinControl;
  I: Integer;
begin
  if (Sender is TWinControl) then
  begin
    Active := TWinControl(Sender);
    StatusBar1.SimpleText := GetLongHint(Active.Hint) + ' mouse over';
  end;
end;

{
Assign this method as the OnActiveControlChange event
handler by setting it from the form's OnCreate event handler.
procedure TForm1.FormCreate(Sender: TObject);
begin
  Screen.OnActiveControlChange := ActiveControlChanged;
end;

{
Make sure you clean up the screen object when the form is
freed by adding this OnDestroy event handler to the form.
procedure TForm1.FormDestroy(Sender: TObject);
begin
  Screen.OnActiveControlChange := nil;
end;

Uses