Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Delayed Event Handling Using Event Handler Detaching for Delphi Applications

Title: Delayed Event Handling Using Event Handler Detaching for Delphi Applications The article How to Detach an Event Handler from a Control Event describes a simple mechanism to remove an event handling procedure from a control's event. The idea can be used to have a click-once button, for example, to have a button on a form that the user can click only once - the event handling code will execute only once. "Delayed" / Controlled Handling Allan Lloyd made a remark about the idea suggesting an extension: when you have an event handler which takes some time ( 0.1 sec) to run, but you don't want another click or a double click to call the event handler a second time before the first call has finished, you can detach the event handler from the event while the event handling code is being executed. Here's a generic implementation of a delayed event handling procedure - the event handler will not be executed the second time until the execution has completed caused by the first click on the button: //handles Button1.OnClick, Button1 on Form1 procedure TForm1.Button1Click(Sender: TObject) ; var SavedOnClick : TNotifyEvent; begin SavedOnClick := TControl(Sender).OnClick; TControl(Sender).OnClick := nil; try // Code which takes some time finally TControl(Sender).OnClick := SavedOnClick; end end; The Sender parameter is used to grab the control that has raised the event, detach the event handling procedure, and attach again when the handler finishes executing. Note that I've hijacked the term "delayed (postponed or asynchronous) event handling" here. Delayed event handling is a term used to describe another programming idea: the TTreeView has a property called DelayTimer which specifies the delay between when a node is selected and when the OnChange event occurs. However, the above trick can also apply for a "delayed event handling" or better to say "controlled event handling" needs :)