directorytree.vb

来自「Samples are organized by chapter, and th」· VB 代码 · 共 81 行

VB
81
字号
Imports System.IO

Public Class DirectoryTree
    Inherits TreeView

    Event DirectorySelected(ByVal sender As Object, ByVal e As DirectorySelectedEventArgs)

    Private _Drive As Char
    Public Property Drive() As Char
        Get
            Return _Drive
        End Get
        Set(ByVal Value As Char)
            _Drive = Value
            If Not Me.DesignMode Then RefreshDisplay()
        End Set
    End Property


    Public Sub RefreshDisplay()

        ' Erase the existing tree.
        Me.Nodes.Clear()

        ' Set the first node.
        Dim RootNode As New TreeNode(_Drive & ":\")
        Me.Nodes.Add(RootNode)

        ' Fill the first level and expand it.
        Fill(RootNode)
        Me.Nodes(0).Expand()

    End Sub

    Private Sub Fill(ByVal DirNode As TreeNode)
        Dim Dir As New DirectoryInfo(DirNode.FullPath)
        Dim DirItem As DirectoryInfo

        ' An exception could be thrown in this code if you don't
        ' have sufficient security exceptions for a file or directory.
        ' You can catch and then ignore this exception.

        For Each DirItem In Dir.GetDirectories
            ' Add node for the directory.
            Dim NewNode As New TreeNode(DirItem.Name)
            DirNode.Nodes.Add(NewNode)
            NewNode.Nodes.Add("*")
        Next

    End Sub

    Protected Overrides Sub OnBeforeExpand(ByVal e As TreeViewCancelEventArgs)
        MyBase.OnBeforeExpand(e)
        ' If a dummy node is found, remove it and read the real directory list.
        If e.Node.Nodes(0).Text = "*" Then
            e.Node.Nodes.Clear()
            Fill(e.Node)
        End If

    End Sub

    Protected Overrides Sub OnAfterSelect(ByVal e As TreeViewEventArgs)
        MyBase.OnAfterSelect(e)
        ' Raise the DirectorySelected event.
        RaiseEvent DirectorySelected(Me, New DirectorySelectedEventArgs(e.Node.FullPath))

    End Sub

End Class


Public Class DirectorySelectedEventArgs
    Inherits EventArgs

    Public DirectoryName As String

    Public Sub New(ByVal directoryName As String)
        Me.DirectoryName = directoryName
    End Sub

End Class

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?