6

I have one button on my form. Following is the click event of that button

procedure Form1.btnOKClick(Sender: TObject);
begin
//Do something
end;

This event will be called only when I click the button, right?

How can I call this event automatically without any user intervention?

1

3 Answers 3

20

The best way to invoke the OnClick event handler attached to a control is to call the Click method on the control. Like this:

btnOK.Click;

Calling the event handler directly forces you to supply the Sender parameter. Calling the Click method gets the control to do all the work. The implementation of the windows message handler for a button click calls the Click method.

But I second the opinion expressed in whosrdaddy's answer. You should pull out the logic behind the button into a separate method.

Sign up to request clarification or add additional context in comments.

8 Comments

+1 This is the only answer that fits perfect the question. OP question is about events and not methods. Maybe OP did not know the difference, but thats the way he asked :o)
It works for click on buttons but there is not such method on Panel for example. Also what about Resize event? How can I call a Resize event programmatically?
@Delmo Either call the event handler directly, or extract it into another method that you can call directly, and which the event handler calls.
Thanks @DavidHeffernan, I supposed this kind of solutions but I was asking for some method to "simulate" an event ocurrence.
As @SirRufo said, the question is about events, not methods.
|
17

Do not put your businesslogic into event handlers. This will make your code unreadable when the application grows larger.

Normally you would do this:

procedure TForm1.DoSomething;
begin
 // do something
end;

procedure TForm1.btnOKClick(Sender: TObject);
begin
 DoSomething;
end;

then all you need to do is call DoSomething from other parts in your code

5 Comments

Same effect as @LURDs answer, only cleaner code. You will thank yourself later if you do it this way, especially if // do something is moved to a separate unit, datamodule, business object.
@whosrdaddy - you are right. I am going to do like that. I asked this question only because I wanted to know the second way.
@GolezTrol: I am re-factoring a 100k LOC behemoth that was written this way, the guy before me needs to be punished :)
Or wrap all the business logic in its own object structure, not related to any GUI.
@JerryDodge: Yes that's something one would normally do :)
8

You can call this event in code like any other method.

...
btnOkClick(Self.btnOk); // Sender in this case is the btnOk
...

The Sender can be whatever object you like or nil.

1 Comment

you did not call the event, you simply call a method. you can't call an event, you can only call the method that is related to an event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.