Mega Code Archive

 
Categories / Delphi / OOP
 

How to add a new event to a component

Title: How to add a new event to a component? Question: How to implement an event... Answer: You can communicate with components via properties, methods and events. Here is a small example how to add an event to DBGrid when the user clicks the right mouse button: type TExtDBGrid = class(TDBGrid) private FOnRightClick : TNotifyEvent; procedure WMRButtonDown(var Message : TWMRButtonDown); message WM_RBUTTONDOWN; protected public published property OnRightClick: TNotifyEvent read FOnRightClick write FOnRightClick; end; procedure TExtDBGrid.WMRButtonDown(var Message: TWMRButtonDown); begin if Assigned(FOnRightClick) then FOnRightClick(Self); end; It's always the same procedure. We need to add a property for the event (in the published section when the event should appear under events in the object-inspector - otherwise in the public section) from the type that defines the parameters of the event. In the above example we used TNotifyEvent type TNotifyEvent = procedure (Sender: TObject) of object; which is defined in the unit Classes and therefore always available! When you want to fire the event you must be sure that the main-program did assign a procedure (assign statement) - then you can call it useing FOnEventName(Self, Params...); In this example we want to react on the right mouse button - this works with the reserved word message and the windows constant for this event: WM_RBUTTONDOWN Of course we can also define custom-events with various parameters. One thing to mention is that you can also use VAR-Parameters, so that the component can get input from the main program. For example: type TMyEvent = procedure (Sender: TObject; VAR aAbort: boolean) of object; procedure TMyComp.AnyFunc; var abort: boolean; begin while (...) do begin if Assigned(FMyEvent) then FMyEvent(Self, abort); if abort then exit; end; end; In this case the event would be fired on every step through the loop and the main program could interrupt assigning aAbort to false !