以编程方式单击按钮

时间:2013-10-03 05:33:29

标签: vb.net winforms button

我想对button进行编码,以便在我点击它时以编程方式点击其他button

例如,我有两个名为Button1Button2的按钮,我想要做的是在点击Button1后立即点击Button2。这可能吗?

5 个答案:

答案 0 :(得分:14)

最佳实施取决于您尝试做的事情。 Nadeem_MK为您提供有效的一个。知道你也可以:

  1. 使用Button2_Click方法提升PerformClick()事件:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
        Me.Button2.PerformClick()
    End Sub
    
  2. 将相同的处理程序附加到许多按钮:

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) _
        Handles Button1.Click, Button2.Click
        'do stuff
    End Sub
    
  3. 使用与Button2_Click方法相同的参数调用Button1_Click(...)方法( IF 您需要知道哪个是发件人):

    Private Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        'do stuff
         Button2_Click(sender, e)
    End Sub
    

答案 1 :(得分:11)

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Button2_Click(Sender, e)
End Sub

此代码调用按钮以编程方式单击事件

答案 2 :(得分:5)

此类情况的最佳做法是创建一个包含所有逻辑的方法,并在两个事件中调用该方法,而不是从另一个事件调用事件;

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        LogicMethod()

End Sub

Private Sub LogicMethod()

     // All your logic goes here

End Sub

如果您需要EventArgs(e)的属性,您可以轻松地通过方法中的参数传递它,如果发件人属于不同类型,则可以避免错误。但是在你的情况下这不会是一个问题,因为两个发件人都是Button类型。

答案 3 :(得分:1)

假设按钮1有一个名为

的事件
Button1_Click(Sender, eventarg)

如果你想在Button2中调用它,那么直接调用这个函数。

Button1_Click(Nothing, Nothing)

答案 4 :(得分:0)

在c#中这是有效的:D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

for vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub