Mega Code Archive

 
Categories / Delphi / Ide Indy
 

How to Detach an Event Handler from a Delphi Control Event

Title: How to Detach an Event Handler from a Delphi Control Event 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: Simulating multicast events in Win32 Delphi Get the list of events with attached event handlers Learn about properties and events in Delphi How to Hook the Mouse to Catch Events Outside of your application How To Share an Event Handler in Delphi