如何通过按Visual Basic中的另一个窗体上的按钮按下窗体上的按钮

时间:2016-11-25 21:50:51

标签: vb.net

我想这是一个简单的问题,但我在这里研究了其他与我无关的相关主题,所以在这里。 通过按Form 2中的特定按钮,出现Form 1,然后按下Form 1中的按钮,必须按下Form 2中的按钮并显示一条消息。我不想使用具有全局变量的模块,因为我已经这样做了办法。有没有办法获取Form1的特定实例而不是新的?这两个类有不同的.vb文件,这里是代码:

Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles form2Btn1.Click
    MsgBox("")
End Sub

Private Sub form2Btn2_Click(sender As Object, e As EventArgs) Handles form2Btn2.Click
    Dim newForm1 As New Form1
    newForm1.ShowDialog()

End Sub
End Class

form1的代码:

Public Class Form1
  Private Sub form1Btn_Click(sender As Object, e As EventArgs) Handles    form1Btn.Click
    Dim newForm2 As New Form2
    newForm2.form2Btn1.PerformClick()

End Sub
End Class

2 个答案:

答案 0 :(得分:0)

剥离Form1 Subs中的私有,即

Public Class Form2
Sub Button1_Click(sender As Object, e As EventArgs) Handles form2Btn1.Click
    MsgBox("")
End Sub

Sub form2Btn2_Click(sender As Object, e As EventArgs) Handles form2Btn2.Click
    Dim newForm1 As New Form1
    newForm1.ShowDialog()
End Sub
End Class

因此,在Form1上,您可以执行类似

的操作
Public Class Form1
  Private Sub form1Btn_Click(sender As Object, e As EventArgs) Handles    form1Btn.Click
    Dim newForm2 As New Form2
    newForm2.Button1_Click(Nothing, Nothing)

End Sub
End Class

答案 1 :(得分:0)

将表单的控件或其事件处理程序暴露给其他类不是很好的练习。但你可以制作公共方法,做同样的工作人员,然后从其他形式调用它 您的解决方案中的主要想法是将Form2的现有/正确实例传递给Form1,如@Plutonix在评论中所建议的那样。

首先从Form1中的button_click eventhandler向公共方法提取逻辑。

Public Class Form2
    Public Sub ShowMessage()
        MsgBox("")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles form2Btn1.Click
        ShowMessage() ' call the method here
    End Sub

    Private Sub form2Btn2_Click(sender As Object, e As EventArgs) Handles form2Btn2.Click
        'Form implements IDisposable interface so
        'it is good practice to wrap that instance with Using statement
        Using newForm1 As New Form1(Me)
            newForm1.ShowDialog()
        End using
    End Sub
End Class

Form1中创建构造函数,该构造函数将此实例作为参数

Public Class Form1
    Private ReadOnly _Form1Instance As Form1

    Public Sub New(form1Instance As Form1)
        _Form1Instance = form1instance;
    End Sub

    Private Sub form1Btn_Click(sender As Object, e As EventArgs) Handles    form1Btn.Click
        'Use instance of Form2 passed through constructor for calling public method
        _Form1Instance.ShowMessage()
    End Sub
End Class