子摘要点击事件

时间:2019-05-24 17:01:24

标签: vb.net

我有一个Windows窗体应用程序,用户可以在其中单击菜单项以打开窗体。单击菜单项后,它将检查表单是否打开,并通知用户表单是否打开,否则将打开表单。的代码如下

Private Sub UsersBarButtonItem_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles UsersBarButtonItem.ItemClick
    If Application.OpenForms().OfType(Of Users).Any Then
        MessageBox.Show("Form Is Open", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
        For Each openform In Application.OpenForms()
            If TypeOf (openform) Is Users Then CType(openform, Users).BringToFront()
        Next
    Else
        Dim Form As New Users
        Form.MdiParent = Me
        Form.Show()
    End If
End Sub

我想要一个子例程来帮助我避免为每个菜单项单击事件重复此代码。

1 个答案:

答案 0 :(得分:0)

好吧,在This线程的帮助下,您可以使用Reflection / linq从其'.Name字符串创建一个新的传递表单实例。如果您找到更好的方法,我会很感兴趣学习自己。

        Private Sub ButtonFormB_Click(sender As Object, e As EventArgs) Handles ButtonFormB.Click

            CheckForm(FormB)

        End Sub

        Private Sub CheckForm(Frm As Form)

            For Each OpnForm As Form In Application.OpenForms
                If OpnForm Is Frm Then
                    OpnForm.BringToFront()
                    Exit Sub
                End If
            Next

            Dim formType =
                Reflection.Assembly.GetExecutingAssembly().GetTypes().Where(Function(a) a.BaseType = GetType(Form) AndAlso a.Name = Frm.Name).FirstOrDefault()

            If formType IsNot Nothing Then
                Dim NewForm As Form = CType(Activator.CreateInstance(formType), Form)
                NewForm.Show()
            End If

        End Sub