如何在不退出应用程序的情况下再次加载表单?

时间:2014-09-10 13:50:36

标签: vb.net

我有2个表格。 Form1和Form2。在form1中有一个按钮,如果点击它将转到form2。如果我单击该按钮,如果form1,form2将加载,整数a将变为1.如果我单击form2中的按钮,整数a将变为0,它将返回到form1。因为我在form1中,如果我再次单击form1中的按钮,它将转到form2但是form2将不会再次加载。是否可以再次加载表单?以下是我的例子:

Form1中:

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Hide()
        Form2.Show()
    End Sub

End Class

窗体2:

Public Class Form2

    Dim a As Integer = 0
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        a = 1
        MsgBox("load complete!!")
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        a = 0
        Me.Hide()
        Form1.Show()
    End Sub

End Class

提前致谢!

2 个答案:

答案 0 :(得分:1)

Form2的Load方法只被调用一次,因为这是表单的正常生命周期。 load表单只在第一次加载表单之前被调用一次。

来自Form.Load Event

  

在首次显示表单之前发生。

解决方案取决于您的需求。如果您需要保留表单的状态,即使它被隐藏,那么您想要使用 VisibleChanged 事件。

Private Sub Form2_VisibleChanged(sender As Object, e As EventArgs) Handles Me.VisibleChanged
    If Me.Visible Then
        MsgBox("Visible changed")
    End If
End Sub

如果您不需要保留状态,则可以丢弃表单2并重新创建它:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Hide()
    Dim Form2 = New Form2()
    Form2.Show()
End Sub


Dim a As Integer = 0
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    a = 1
    MsgBox("load complete!!")
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    a = 0
    Form1.Show()
    Me.Close()
End Sub

答案 1 :(得分:0)

在加载Form2之前,只需设置一个新的Form2实例。

 Dim Form2 As New Form2
 Form2 .Show()