Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 36 ยท Forms and Tooling

Events and the IDE

Learn how Delphi events work as method pointers, how to write and assign handlers, how the Windows message loop drives forms, and how to keep an interface responsive.

A console program decides what happens next. A window program waits for the user to decide. It sits idle until a click, a key press, a timer tick or a message from the system arrives, and then runs the code you attached to that occurrence. That style is event-driven programming, and Delphi makes it feel natural: an event is a property whose value is a procedure.

This lesson explains what an event really is, how handlers are connected, what the message loop does, and how to avoid freezing the screen.

An event is a method pointer

Click a button in the designer, open the Events tab of the Object Inspector and double-click OnClick. The IDE creates an empty method and fills in the link:

PASCAL
procedure TMainForm.SaveButtonClick(Sender: TObject);
begin
  // your code runs when the button is clicked
end;

Sender is the component that raised the event, so several controls can share one handler and tell themselves apart:

PASCAL
procedure TMainForm.ColorButtonClick(Sender: TObject);
begin
  if Sender = RedButton then
    Panel1.Color := clRed
  else if Sender is TButton then
    Panel1.Caption := TButton(Sender).Caption;
end;

The type of OnClick is TNotifyEvent, declared in the VCL as:

PASCAL
type
  TNotifyEvent = procedure(Sender: TObject) of object;

The words of object matter. An ordinary procedure pointer holds one address. A method pointer holds two: the address of the code and the address of the object it belongs to (Self). That is how a click on a button reaches a method of your form, with Self set correctly.

You can attach handlers in code too:

PASCAL
SaveButton.OnClick := SaveButtonClick;
SaveButton.OnClick := nil;      // detach; events are optional

Components therefore never need to know about your form. They only call whatever is stored in their event property, after checking that it is assigned:

PASCAL
procedure TMyButton.DoClick;
begin
  if Assigned(FOnClick) then
    FOnClick(Self);
end;

Defining your own events

The same pattern works for your own classes. Declare a method pointer type, a field, and a published or public property:

PASCAL
type
  TTemperatureEvent = procedure(Sender: TObject; Celsius: Double) of object;

  TSensor = class
  strict private
    FOnReading: TTemperatureEvent;
  public
    procedure Measure;
    property OnReading: TTemperatureEvent read FOnReading write FOnReading;
  end;

procedure TSensor.Measure;
begin
  if Assigned(FOnReading) then
    FOnReading(Self, 21.5);
end;

This is the observer pattern in a few lines. For several listeners, keep a list of method pointers yourself, or use anonymous methods (see generics and anonymous methods) and TProc<Double>.

Common events

Event When it fires
OnClick the user clicks (or presses Enter or Space on a focused button)
OnChange text or selection changed
OnKeyPress, OnKeyDown a key is pressed
OnMouseMove, OnMouseDown the mouse moves or is pressed
OnCreate, OnShow, OnClose, OnCloseQuery form lifetime; OnCloseQuery can cancel closing
OnTimer a TTimer interval elapses
OnPaint a control needs to be drawn

OnCloseQuery is the right place for "Save changes?" dialogs:

PASCAL
procedure TMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
  if FModified then
    CanClose := MessageDlg('Discard changes?', mtConfirmation,
                           [mbYes, mbNo], 0) = mrYes;
end;

The message loop

Behind every Windows program is a loop that fetches messages and dispatches them:

flowchart LR
  Q["Message queue<br/>click, key, timer, paint"] --> L["Application.Run<br/>message loop"]
  L --> D["Dispatch to the window"]
  D --> H["Your event handler"]
  H --> L

The loop calls your handler, and nothing else happens until the handler returns.

Application.Run is that loop. The consequence is the most important rule of GUI programming: while your handler is running, the window cannot repaint, move or react. A handler that loops for ten seconds freezes the window for ten seconds ("Not Responding").

Ways to stay responsive:

  • Keep handlers quick; split long work into small steps driven by a TTimer.
  • Run slow work in a thread (TThread, TTask.Run from System.Threading) and report back with TThread.Queue or TThread.Synchronize, because only the main thread may touch controls.
  • Show a progress bar and update it from the main thread.
  • As a last resort in old code, call Application.ProcessMessages inside a loop so waiting messages are handled. It works but invites re-entrancy bugs: the user can click the same button again while the first handler is still running.

An event loop in C

The program below models the queue and the loop. Handlers are registered as a function plus a context pointer, the C version of a method pointer with its Self. The loop pulls events off a queue and dispatches them until a "quit" arrives.

C Stand-in: a message queue and dispatch loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Each event runs to completion before the next is fetched, which is exactly why a long handler blocks the interface.

Getting around the IDE

You will use these daily (Delphi defaults; Lazarus is similar but uses different key chords):

  • F9 build and run, Ctrl+F9 compile only, Shift+F9 build all.
  • F12 switch between form and code, Ctrl+Shift+Up/Down jump between a declaration and its implementation.
  • Ctrl+Space code completion, Ctrl+Shift+Space parameter hints, Ctrl+Click go to declaration.
  • F8 step over, F7 step into, F5 toggle a breakpoint (more in debugging and compiler tools).
  • The Object Inspector edits properties and events of the selected component; the Structure view shows the component tree; the Project Manager lists your units.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does of object in procedure(Sender: TObject) of object change?

    A method pointer carries two pieces, so a button can call a method of your form with the correct Self.
  2. 2. Why does a ten-second loop in a button handler freeze the window?

    Handlers run on the main thread that also runs the message loop, so everything waits.
  3. 3. Why test Assigned(FOnClick) before calling it?

    An event property is nil until someone attaches a handler. Calling it unchecked causes an access violation.
  4. 4. What is the safe way for a worker thread to update a label?

    Only the main thread may touch visual controls; Queue and Synchronize run your code there.

Summary

  • An event is a property holding a method pointer (of object): code address plus Self.
  • Handlers receive Sender; one handler can serve many controls.
  • Check Assigned before calling an event you define; use the same pattern for your own events.
  • The message loop runs handlers one at a time on the main thread: keep them short or move work to threads.
  • Learn the IDE shortcuts: F9, F12, Ctrl+Space, F7/F8, F5.

Next: Debugging and Compiler Tools