读书人

一个有关问题:怎么动态添加Menuscrip

发布时间: 2012-01-30 21:15:58 作者: rapoo

请教高手一个问题:如何动态添加Menuscrip的某个项的子项?
实现如下内容:窗体启动时,获取系统的硬盘分区,并将每个分区作为菜单项添加到Menuscript的“我的电脑”项下,代码如下,请高手看看,为何运行后窗体无法看到(本来已经实现,后来改了之后就看不到窗体了)?
并且请教一下:如何实现单击动态添加的菜单项实现Click事件(如打开对应的分区)?我不知道如何对不同的刚添加的菜单项进行操作!谢谢!


Friend WithEvents Drive_item As New System.Windows.Forms.ToolStripMenuItem
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Drives As System.IO.DriveInfo() = System.IO.DriveInfo.GetDrives
For Each info As System.IO.DriveInfo In Drives
Drive_item.Text = info.VolumeLabel.ToString & " ( " & info.Name.Trim( "\ ") & ") "
Drive_item.Name = info.Name.Trim( "\ ").Trim( ": ")
我的电脑ToolStripMenuItem.DropDown.Items.Add(Drive_item.Text)

Next
End Sub

[解决办法]
Friend WithEvents Drive_item As New System.Windows.Forms.ToolStripMenuItem
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Drives() As System.IO.DriveInfo = System.IO.DriveInfo.GetDrives
For Each info As System.IO.DriveInfo In Drives
If info.IsReady Then
Drive_item.Text = info.VolumeLabel.ToString & " ( " & info.Name.Trim( "\ ") & ") "
Drive_item.Name = info.Name.Trim( "\ ").Trim( ": ")
Else
Drive_item.Text = "( " & info.Name.Trim( "\ ") & ") " '驱动器访问错误
End If
我的电脑ToolStripMenuItem.DropDown.Items.Add(Drive_item.Text)
Next
End Sub
[解决办法]
你的程序没有报错还是比较幸运的,在你提供的程序段第5行, info.VolumeLabel是返回当前盘的卷标,这个方法正确执行的前提是检测驱动器就绪,也就是说驱动器内有磁盘,这对于硬盘来说也许不算什么,但对于软盘、光驱等移动磁盘设备,当没有盘片时,调用info.VolumeLabel就会抛出一个错误,因为驱动器未就绪。你很幸运,没有软盘驱动器和光驱,所以程序没有报错,但在其他用户那里就不一定通过了。而解决这个错误就要先检测驱动器是否就绪,DriveInfo的IsReady属性返回一个布尔值,告诉用户驱动器是否就绪,于是也就有了我上面的写法,你可以看看,我觉得是没有问题的~~~

click事件可以这样触发:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
我的电脑ToolStripMenuItem.DropDown.Items.Add( "haha ", Nothing, New EventHandler(AddressOf clickme))
我的电脑ToolStripMenuItem.DropDown.Items.Add( "hhhh ", Nothing, New EventHandler(AddressOf clickme))
End Sub

Private Sub clickme(ByVal sender As System.Object, ByVal e As System.EventArgs)
MsgBox(sender.text)
End Sub

你参考一下,我不太明白你要做什么,只能先这样了

读书人网 >VB Dotnet

热点推荐