使用另一个Sub为Button / ToolStripMenuItem提供代码

时间:2013-03-28 22:38:55

标签: vb.net

所以,我想让我的应用程序播放视频文件。您可以通过ToolStripMenuItem选择一个。我使代码几乎成为所有500个ToolStripMenuItem的allrounder。 我要遵守的准则:

Dim Inst As String = My.Computer.FileSystem.SpecialDirectorys.ProgramFiles + "\folder\"

Private Sub PlayVid(Name)
    AxWindowsMediaPlayer1.URL = Inst + IO.File.ReadAllLines(Inst + "directorys.txt")(Name.Txt.Substring(0, 3))
End Sub

Private Sub ToolStripMenuItem1_Click(sender As System.Objekt) ToolStripMenuItem1.Click
    Call PlayVid(Ctype(sender, ToolStripMenuItem))
End Sub

所以现在我需要为每个ToolStripMenuItem分配的代码很短,但我仍然需要为500多个代码执行此操作。所以我的问题是,如果有一种方法(可能在Form.Load中)将此(调用PlayVid(Ctype(发送者,ToolStripMenuItem)))代码分配给每个人。类似的东西:

Private Sub Form_Load() Handles MyBase.Load
    Dim T As Control
    For Each T in Controls
        If TypeOf C is ToolStripMenuItem Then
            C.Code = Call PlayVid(Ctype(sender, ToolStripMenuItem))
        End If
    Next
End Sub

这样的事情是否可能?如果是这样,它是如何工作的?

1 个答案:

答案 0 :(得分:0)

500个菜单项?哇。

无论如何,当您创建菜单项时,其中一个参数用于单击处理程序:

Dim tsm As New ToolStripMenuItem("YourFile", Nothing, AddressOf PlayVid)

您的PlayVid方法应具有匹配点击事件的相应参数:

Private Sub PlayVid(sender As Object, e As EventArgs)

End Sub

ToolStripMenuItems不是传统意义上的控件。引用您的父菜单项:

For Each menuItem As ToolStripMenuItem In ToolStripDropDownButton1.DropDownItems

Next