Unit1
looks like this:
unit Unit1;
interface
uses
SysUtils, Types, Classes,
Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
uses Unit2;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Form2.ShowModal;
end;
end.
Unit1
creates a class named
TForm1
(derived from TForm) and an instance of this class,
Form1
.
TForm1
includes
a
buttonButton1
, an instance of TButton and a procedure named
Button1Click
that is called when the user
presses
Button1
.
Button1Click
hides
Form1
and
it displays
Form2
(the call to
Form2.ShowModal
).
Note:
In the previous example,
Form2.ShowModal
relies on the use of auto-created forms. While this is fine for
example code, using auto-created forms is actively discouraged.
Form2
is defined in
Unit2
:
unit Unit2;
interface
uses SysUtils, Types, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm2 = class(TForm)
Label1: TLabel;
CancelButton: TButton;
procedure CancelButtonClick(Sender: TObject);
end;
var
Form2: TForm2;
implementation
11
uses Unit1;
{$R *.dfm}
procedure TForm2.CancelButtonClick(Sender: TObject);
begin
Form2.Close;
end;
end.
Unit2
creates a class named
TForm2
and an instance of this class,
Form2
.
TForm2
includes a button
(
CancelButton
, an instance of TButton) and a label (
Label1
, an instance of TLabel). You can't see this from the
source code, but
Label1
displays a caption that reads Hello world! The caption is defined in
Form2
's form file, Unit2.
dfm.
TForm2
declares and defines a method
CancelButtonClick
which will be invoked at runtime whenever the user
presses
CancelButton
. This procedure (along with
Unit1
's
TForm1.Button1Click
)
is called an event
handler because it responds to events that occur while the program is running. Event handlers are assigned to
specific events by the form files for
Form1
and
Form2
.
When the
greeting
program starts,
Form1
is displayed and
Form2
is invisible. (By default, only the first form
created in the project file is visible at runtime. This is called the project's main form.)
When the user presses the
button on
Form1
,
Form2
, displays the Hello world! greeting. When the user presses the
CancelButton
or the
Close
button on the title bar,
Form2
closes.
12