Pergunta

I have a few menu items in my project that open new forms when clicked and every time I click on one I run the code below. However I have to add it for each MenuItem_Click event, so whenever I change the code I have to copy and past between forms. FormName is the only thing that changes. All of my menu items are named after the corresponding form, mi_FormName. And I know how to make a general event handler.

Is there any way to make it grab the name of the clicked on menu item, remove the mi_, and insert it in the same places as FormName?

   Private Sub MenuItem_Click(sender As Object, e As EventArgs) Handles MenuItem.Click

    Dim F As Form
    If Not IsNothing(modForms.CheckOpen("FormName")) Then
        F = modForms.CheckOpen("FormName")
        If F.IsDisposed Then
            modForms.CheckOpen.Remove("FormName")
            F = New FormName
            F.Show()
        ElseIf F.Visible = False Then
            F.Show()
        Else
            F.BringToFront()
        End If
    Else
        F = New FormName
        F.Show()
    End If

End Sub
Foi útil?

Solução

Why not just use a lambda that passes along the type of the form? You can use GetType to find the textual name and use a simple constraint to allow instances to be created

AddHandler mi_FormName.Click, Sub(s, e) OnClick(Of FormName)
AddHandler mi_OtherForm.Click, Sub(s, e) OnClick(Of OtherForm)

The click handler would look essentially as follows

Private Sub OnClick(Of T As {New, Form})()
    Dim name = GetType(T).Name
    Dim F As Form
    If Not IsNothing(modForms.CheckOpen(name)) Then
        F = modForms.CheckOpen(name)
        If F.IsDisposed Then
            modForms.CheckOpen.Remove(name)
            F = New T
            F.Show()
        ElseIf F.Visible = False Then
            F.Show()
        Else
            F.BringToFront()
        End If
    Else
        F = New T
        F.Show()
    End If
End Sub
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top