Public Sub在两个表单之间切换

时间:2017-12-12 22:54:36

标签: vb.net

我正在尝试在菜单条上使用此Public Sub。它不是切换表单,而是打开frmEmployee表单的另一个实例。员工表格首先打开。如何隐藏打开的表单并打开其他表单?谢谢!

Public Sub SwitchForm()
    Dim F1 As New frmEmployee
    Dim F2 As New frmEvaluation
    If F1.Visible = True Then
        F1.Hide()
        F2.Show()
    Else
        F2.Hide()
        F1.Show()
    End If
End Sub

3 个答案:

答案 0 :(得分:0)

您在函数范围内声明了变量F1F2。因此,每次调用该函数时,它都会创建这些表单的两个新实例,并且检查F1.Visible是没有意义的,因为它不会引用旧实例,而是引用刚刚创建的实例。

答案 1 :(得分:0)

这是可以玩的东西......

status 500

答案 2 :(得分:0)

更新了答案。

这是一个似乎对我有用的例子。您可能需要根据表单的声明和创建方式进行调整,但它对我有用..

Public Class Form1

    Dim WithEvents frm1 As New Form
    Dim WithEvents frm2 As New Form

    Dim formWithFocus As String = ""

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        frm1.Location = New Point(100, 100)
        frm1.Size = New Size(100, 100)
        frm1.Name = "frm1"
        frm2.Location = New Point(200, 200)
        frm2.Size = frm1.Size
        frm2.Name = "frm2"
        frm1.Show()
        frm2.Show()
    End Sub
    Private Sub frm_gotFocus(sender As Object, e As EventArgs) Handles frm1.GotFocus, frm2.GotFocus
        If sender Is frm1 Then
            formWithFocus = "frm1"
        ElseIf sender Is frm2 Then
            formWithFocus = "frm2"
        End If
        formWithFocus = CType(sender, Form).Name
    End Sub

    Private Sub switchform()
        If formWithFocus = "frm1" Then
            RemoveHandler frm1.GotFocus, AddressOf frm_gotFocus
            RemoveHandler frm2.GotFocus, AddressOf frm_gotFocus
            frm2.Select()
            formWithFocus = "frm2"
            AddHandler frm1.GotFocus, AddressOf frm_gotFocus
            AddHandler frm2.GotFocus, AddressOf frm_gotFocus
        ElseIf formWithFocus = "frm2" Then
            RemoveHandler frm1.GotFocus, AddressOf frm_gotFocus
            RemoveHandler frm2.GotFocus, AddressOf frm_gotFocus
            frm1.Select()
            formWithFocus = "frm1"
            AddHandler frm1.GotFocus, AddressOf frm_gotFocus
            AddHandler frm2.GotFocus, AddressOf frm_gotFocus
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        switchform()
    End Sub
End Class