Fandom

Delphi Programming

Event Handlers in Delphi

2,918pages on
this wiki
Add New Page
Talk0 Share

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.

The two most obvious differences between the VB and Delphi code are:

  1. The Delphi example uses more code.
  2. The VB example requires more visual elements.

Aside from that, this example shows how powerful Delphi's VCL framework is because the visual controls are created on the fly. As you can imagine this is a lot more flexible than the VB example. Also, the event handlers are not hard-wired and can even be changed at runtime because of Delphi's support for delegates.


 unit Unit1;
 
 interface
 
 uses
   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
   Dialogs, StdCtrls, Contnrs;
 
 type
   TForm1 = class(TForm)
 
     procedure FormCreate(Sender: TObject);
 
   private
     m_Labels: TObjectList;
     m_EditBoxes: TObjectList;
     m_LabelCaptions: TStringList;
 
     procedure EditBoxEnterHandler(Sender: TObject);
     procedure EditBoxExitHandler(Sender: TObject);
 
   public
   end;
 
 var
   Form1: TForm1;
 
 implementation
 
 {$R *.dfm}
 
 procedure TForm1.FormCreate(Sender: TObject);
 var
   index:        Integer;
   aLabel:       TLabel;
   editBox:      TEdit;
 begin
   m_LabelCaptions := TStringList.Create();
   m_Labels := TObjectList.Create(False);
   m_EditBoxes := TObjectList.Create(False);
   for index := 0 to 4 do
   begin
     aLabel := TLabel.Create(self);
     aLabel.Left := 10;
     aLabel.Parent := self;
     aLabel.Top := 10 + index * 24;
     aLabel.Height := 18;
     aLabel.Width := 80;
     aLabel.Visible := True;
     aLabel.Caption := Format('Label%d', [index + 1]);
     m_LabelCaptions.Add(aLabel.Caption);
     m_Labels.Add(aLabel);
     editBox := TEdit.Create(self);
     editBox.Parent := self;
     editBox.Top := aLabel.Top;
     editBox.Visible := True;
     editBox.Height := 18;
     editBox.Width := 80;
     editBox.Left := 90;
     editBox.OnExit := EditBoxExitHandler;
     editBox.OnEnter := EditBoxEnterHandler;
     m_EditBoxes.Add(editBox);
   end;
 end;
 
 procedure TForm1.EditBoxExitHandler(Sender: TObject);
 var
   idx: Integer;
 begin
   idx := m_EditBoxes.IndexOf(Sender as TEdit);
   (m_Labels[Idx] as TLabel).Caption := m_LabelCaptions[idx];
 end;
 
 procedure TForm1.EditBoxEnterHandler(Sender: TObject);
 var
   idx: Integer;
 begin
   idx := m_EditBoxes.IndexOf(Sender as TEdit);
   (m_Labels[idx] as TLabel).Caption := 'Enter-->';
 end;
 
 end.

Also on Fandom

Random Wiki