13 Votes

Delphi: Declare Default (OnClick) Event for Custom Control

Tip by Delphian | Last update on 2023-01-29 | Created on 2013-04-19

When writing your own components using Delphi or Lazarus, sometimes, it is useful to declare an own default event for an event handler. For example, whenever the user clicks with the mouse on your component, a default action should be performed automatically. And this without assigning a specific procedure when using the component.

In this tip, I would like to show you, how you can implement that. We would like to have a look at the following code:

TMyComponent = class(...)
  private 
    ...
  public
    procedure Click; override,
    ...
  published
    ...
end;   

...

procedure TMyComponent.Click;
begin
   inherited;  
   // YOUR CODE
end;

As you can see, you should not overwrite the OnClick event of the component, because this is something, only the user of the component should do (for example, by using the Object Inspector, when making use of the component).

Instead, we override the event that is calling OnClick internally. This is the procedure Click. We define our own Click procedure and within, we are calling "inherited" which is making sure, that the standard click behavior like the OnClick event of the user is carried out. Depending on whether you would like to have carried out your own event treatment before or after the inherited call, you can put the inherited call before, after or even in your own code (or not at all if we want to define conditions for it).

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.