Visual Basic程式選單大部分都是在設計時期,在編譯程式設定的
透過Visible屬性來設定選項的顯示與否
不過也可以透過程式碼來新增選單項目
引用:
作者: Form1.vb
Imports System.IO
Public Class Form1
Dim ToolStripMenuItem(20) As ToolStripMenuItem
Dim ad As DriveInfo() = DriveInfo.GetDrives
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Single, j As Single = 0
For i = 0 To ad.Count - 1
If ad(i).IsReady Then
ToolStripMenuItem(j) = New System.Windows.Forms.ToolStripMenuItem
ToolStripMenuItem(j).Text = ad(i).Name & ad(i).VolumeLabel
ToolStripMenuItem(j).Tag = i
DriveToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripMenuItem() {ToolStripMenuItem(j)})
AddHandler ToolStripMenuItem(j).Click, AddressOf ToolStripMenuItem_Click
j += 1
End If
Next
'For Each md As DriveInfo In ad
'If md.IsReady Then
'End If
'Next
End Sub
Private Sub ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
TextBox1.Text = "磁碟機代號: " & ad(sender.tag).Name & vbCrLf _
& "磁碟標籤: " & ad(sender.tag).VolumeLabel & vbCrLf _
& "磁碟類型: " & ad(sender.tag).DriveType.ToString & vbCrLf _
& "磁碟格式: " & ad(sender.tag).DriveFormat & vbCrLf _
& "磁碟大小: " & ad(sender.tag).TotalSize.ToString & vbCrLf _
& "剩餘空間: " & ad(sender.tag).AvailableFreeSpace.ToString
End Sub
End Class
|
由於我們必須要利用DriveInfo讀取磁碟機的資訊,所以必須下Imports System.IO指令,不然程式會"不認識"DriveInfo
引用:
Friend WithEvents MenuStrip1 As System.Windows.Forms.MenuStrip
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents DriveToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
|
表單上只放2個元件MenuStrip1元件以及TextBox1元件,TextBox1元件的Multiline 必須設為 True,然後在MenuStrip1元件在加入一個ToolStripMenuItem
引用:
AddHandler ToolStripMenuItem(j).Click, AddressOf ToolStripMenuItem_Click
|
這是將ToolStripMenuItem(j)的Click事件指向ToolStripMenuItem_Click程式段
當被點選的項目執行該程式段時,sender代表的便是該項目的指標,而再將項目加到DriveToolStripMenuItem時
已經將該項目的Index資訊存入tag屬性
(ToolStripMenuItem(j).Tag = i)
所以我們只需要取出該屬性值,就可以知道使用者點選哪個項目
("磁碟機代號: " & ad(sender.tag).Name & vbCrLf _)