How can I simulate the press of a button?

杀马特。学长 韩版系。学妹 提交于 2019-12-01 17:44:29

The cleanest approach is to call the Click method of the button. This is better than the alternatives for these reasons:

  • You could read the OnClick property, check that it was not nil, and then call the method. But that seems rather pointless since the Click method already does just that. There's no point duplicating this code.
  • And you could call the event handler directly, but that would require your code to have knowledge of it. That implies an undesirable level of coupling to the implementation details.
  • Calling Click replicates what actually happens when the user clicks. It is what happens when the user presses the button. It deals with any actions that are associated with the button, for example. It sets the forms ModalResult property. And so on.
bejarun

btn_ok.click or btn_okClick(sender);

Ungureanu Serban

Calling the OnClick event handler won't call the Delphi's default event handler, but just the one implemented by the user. I think you should create your own class derived from TCustomButton, and implement a function that calls the Click method(it is protected).

A correction for TSpeedButton:

The behavior described by @David Heffernan does not quite hold true for speedbuttons in a group. Calling the Click method does not seem to affect the "Down" status of the buttons.

To solve this I used the following code:

MyButton.Click;
MyButton.Down := True;
Andy Nikolov

It's better to use the PerformClick() method of the Button =>

button1.PerfomClick()

If your Button is not in the right state to click (enabled false or not visible), it will not perform the click eventmethod.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!