How can I simulate the press of a button?

前端 未结 5 709
天命终不由人
天命终不由人 2021-01-18 15:25

I want to test some forms. Is there a way to simulate the press of an Ok (or Cancel) button so that the button is pressed and fires the event handlers that are associated wi

相关标签:
5条回答
  • 2021-01-18 16:08

    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.

    0 讨论(0)
  • 2021-01-18 16:17

    btn_ok.click or btn_okClick(sender);

    0 讨论(0)
  • 2021-01-18 16:22

    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.
    0 讨论(0)
  • 2021-01-18 16:25

    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;
    
    0 讨论(0)
  • 2021-01-18 16:29

    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).

    0 讨论(0)
提交回复
热议问题