包含MenuStrip控件的父窗体

时间:2017-11-14 18:05:24

标签: vb.net winforms

我有一个简单的桌面应用程序,我一直在构建。目前,它使用一堆按钮在表单之间来回导航。

现在我决定在顶部添加一个小的MenuStrip控件来帮助导航。

我目前在每个表单中都有相同的MenuStrip,重复代码如下:

Private Sub AddEngineToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AddEngineToolStripMenuItem.Click
    Dim frmShowEnginesForm = New frmShowEnginesForm()
    frmShowEnginesForm.Show()
    Me.Hide()
End Sub

Private Sub EnterSpecsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EnterSpecsToolStripMenuItem.Click
    Dim frmEnterEngineSpecsForm = New frmEnterEngineSpecsForm()
    frmEnterEngineSpecsForm.Show()
    Me.Hide()
End Sub

我希望能够简化这一点,所以如果我想要添加另一个菜单项,我就不必浏览所有表格并将其全部更改。

有没有办法创建包含MenuStrip的排序父控件/表单,所以我不必在所有表单中复制它?

谢谢!

1 个答案:

答案 0 :(得分:2)

将新的Module Module1 Public Sub CreateMenuStrip(frm As Form) 'create new MenuStrip control Dim ms As New MenuStrip ms.Location = New Point(0, 0) ms.Dock = DockStyle.Top 'create new toolstripmenuitem Dim itm As New ToolStripMenuItem itm.Name = "miAddEngine" itm.Text = "Add Engine" 'add handler what will happen when you click on this item... same for next item AddHandler itm.Click, AddressOf AddEngineToolStripMenuItem_Click ms.Items.Add(itm) itm = New ToolStripMenuItem itm.Name = "miEnterSpecs" itm.Text = "Enter Specs" AddHandler itm.Click, AddressOf EnterSpecsToolStripMenuItem_Click ms.Items.Add(itm) '... 'there you can, latter, add new item and bellow sub add subs which will handle click or whatever '... 'add control to the form frm.Controls.Add(ms) End Sub 'subroutines which will handle Click Private Sub AddEngineToolStripMenuItem_Click(sender As Object, e As EventArgs) MsgBox("open add engine form") End Sub Private Sub EnterSpecsToolStripMenuItem_Click(sender As Object, e As EventArgs) MsgBox("open enter specs form") End Sub End Module 添加到您的项目中并使用以下代码:

CreateMenuStrip(Me)

现在,从您的每个表单加载后,请致电Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load CreateMenuStrip(Me) End Sub

例如,在Form1中:

MDI Form

当然,您始终可以创建MenuStrip和他的孩子,将MDIForm放在webpack --display-error-details的顶部。