Delphi Programming

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

How to Detach an Event Handler from a Control Event

By Zarko Gajic, About.com

Almost all the code you write in your Delphi applications is executed, directly or indirectly, in response to events. Events are being raised by components, when a certain situation "happens". For example, when a user clicks a button, an OnClick event is being raised. You, as a developer, can handle (react to) this event by writing an event handler.

Suppose you have placed a TButton (named "Button1") control on a form (named "Form1"), the handler for the OnClick event might look like:

procedure TForm1.Button1Click(Sender: TObject) ;
begin
   ShowMessage('Who clicked?') ;
end;

Remove (Detach, Disable) Event Handler from Event

If, for any reason, you want to detach (remove) the code you have written in an event handler, you have to set the event handler to nil.

For example, here's how to remove the event handler for the Button1's OnClick event:

Button1.OnClick := nil;

To create a "click-once" button, you could use the following code in the button's OnClick handler:

procedure TForm1.Button1Click(Sender: TObject) ;
begin
  ShowMessage('Who clicked?') ;
  //remove event handler from event
  Button1.OnClick := nil;
end;
When a user clicks on Button1, the message ("Who clicked?") will be displayed. The next time the user tries to click the button - nothing will happen.

To re-assign the procedure Button1Click to the Button1's OnClick event, you should use the next call:

Button1.OnClick := Button1Click;

Related tips / tutorials:

Delphi tips navigator:
» Drawing a Focus Rectangle Around the Active Control
« How to Draw a Gradient Fill on a Canvas

More Delphi Programming Quick Tips

Explore Delphi Programming

About.com Special Features

Delphi Programming

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. How to Detach an Event Handler from a Delphi Control Event

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

All rights reserved.