none
Populating a listbox with files / folders from a root folder path RRS feed

  • Question

  • Hi

    I have been working on a personal project that has a project folder per job. currently, that project folder location is set as a path in the Database. The path is E:\Projects\ClientName

    from there, i am trying to make it so that when i select the Client from a list, the folder for that client (clients name is also saved in the Database) is selected and the folders of that folder are displayed in a Treeview (under the root Client folder). If i click a folder in the treeview, the contents are shown in a listbox on the right. Only the files of a selected folder are shown in the listbox on the right and only the folders & subfolders are shown in the treeview on the left.

    Did find a few topics on System.IO but nothing that i would be similar to what i am trying to achieve.

    Does anyone have any good links that i can be referred to?

    Something like this

    Also, im sure i could filter the listbox but it only needs to show certain filetypes and the icons:

    .IDW

    .IPT

    .IAM

    .XLS

    .PDF

    .JPG

    .DWG

    .DXF

    NOTE: I can displays the icons using the DevExpress toolkit i have easily enough

    Appreciate any help

    Nacho


    Nacho is the derivative of Nigel - True fact! I am self taught in VB.Net. 50% of the time, I am right 100% of the time!

    Tuesday, November 6, 2018 11:11 PM

All replies

  • Hi

    Here is some code to show filtered file list in a ListBox.

    ' Form1 with ListBox1
    Option Strict On
    Option Explicit On
    Public Class Form1
      Dim path As String = My.Computer.FileSystem.SpecialDirectories.Desktop & "\New folder"
      Dim filters As List(Of String) = {"*.idw", "*.ipt", "*.iam", "*.xls", "*.pdf", "*.jpg", "*.dwg", "*.dxf"}.ToList
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.DataSource = GetFiles(path)
      End Sub
      Function GetFiles(p As String) As List(Of String)
        Dim so As IO.SearchOption = IO.SearchOption.AllDirectories
        Dim results As New List(Of String)
        For Each filter As String In filters
          results.AddRange(IO.Directory.GetFiles(p, filter, IO.SearchOption.AllDirectories))
        Next
        Return results
      End Function
    End Class


    Regards Les, Livingston, Scotland

    Wednesday, November 7, 2018 12:04 AM
  • Hi,

    I think you can use listview control.

    Imports System.IO
    
    Public Class Form1
        Dim fullPath As String = "D:\test"
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            TreeView1.Nodes.Clear()
            Dim dirs As DirectoryInfo = New DirectoryInfo(fullPath)
            Dim dir As DirectoryInfo() = dirs.GetDirectories()
            Dim file As FileInfo() = dirs.GetFiles()
            Dim dircount As Integer = dir.Count()
            Dim filecount As Integer = file.Count()
    
            For i As Integer = 0 To dircount - 1
                TreeView1.Nodes.Add(dir(i).Name)
                Dim pathNode As String = fullPath & "\" & dir(i).Name
                GetMultiNode(TreeView1.Nodes(i), pathNode)
            Next
    
            For j As Integer = 0 To filecount - 1
                TreeView1.Nodes.Add(file(j).Name)
            Next
        End Sub
        Private Function GetMultiNode(ByVal treeNode As TreeNode, ByVal path As String) As Boolean
            If Directory.Exists(path) = False Then
                Return False
            End If
    
            Dim dirs As DirectoryInfo = New DirectoryInfo(path)
            Dim dir As DirectoryInfo() = dirs.GetDirectories()
            Dim file As FileInfo() = dirs.GetFiles()
            Dim dircount As Integer = dir.Count()
            Dim filecount As Integer = file.Count()
            Dim sumcount As Integer = dircount + filecount
    
            If sumcount = 0 Then
                Return False
            End If
    
            For j As Integer = 0 To dircount - 1
                treeNode.Nodes.Add(dir(j).Name)
                Dim pathNodeB As String = path & "\" & dir(j).Name
                GetMultiNode(treeNode.Nodes(j), pathNodeB)
            Next
    
            For j As Integer = 0 To filecount - 1
                treeNode.Nodes.Add(file(j).Name)
            Next
    
            Return True
        End Function
    
        Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
            ListView1.Clear()
            ListView1.View = View.Details
            ListView1.LabelEdit = True
            ListView1.AllowColumnReorder = True
            ListView1.CheckBoxes = False
            ListView1.FullRowSelect = True
            ListView1.GridLines = True
            ListView1.Sorting = SortOrder.Ascending
            ListView1.Columns.Add("Description", 60, HorizontalAlignment.Left)
            ListView1.Columns.Add("DateTime", 100, HorizontalAlignment.Left)
            ListView1.Columns.Add("Link", -2, HorizontalAlignment.Left)
            Dim f As String = TreeView1.SelectedNode.FullPath
            Dim nume As String = Path.GetFileName(f)
            Dim items As ListViewItem = New ListViewItem(nume)
            Dim vlist1 As ListViewItem.ListViewSubItem = New ListViewItem.ListViewSubItem()
            Dim fl As FileInfo = New FileInfo(fullPath & "\" & nume)
            vlist1.Text = fl.CreationTime.ToString
            items.SubItems.Add(vlist1)
            ListView1.Items.Add(items)
        End Sub
    
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, November 7, 2018 6:50 AM
  • Hi

    Appreciate the replies.

    @Alex - Yes something similar to that except the tree on the left only shows the folders and the list on the right only shows the contents of those folders as they are selected. Files cannot be shown in the left panel, only folders in the structure they are in :)

    Thanks

    Nacho


    Nacho is the derivative of Nigel - True fact! I am self taught in VB.Net. 50% of the time, I am right 100% of the time!

    Wednesday, November 7, 2018 6:55 AM
  • Hi,

    this effect?

    code:

    Imports System.IO
    
    Public Class Form1
        Dim fullPath As String = "D:\test"
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            TreeView1.Nodes.Clear()
            Dim dirs As DirectoryInfo = New DirectoryInfo(fullPath)
            Dim dir As DirectoryInfo() = dirs.GetDirectories()
            Dim file As FileInfo() = dirs.GetFiles()
            Dim dircount As Integer = dir.Count()
            Dim filecount As Integer = file.Count()
    
            For i As Integer = 0 To dircount - 1
                TreeView1.Nodes.Add(dir(i).Name)
                Dim pathNode As String = fullPath & "\" & dir(i).Name
                GetMultiNode(TreeView1.Nodes(i), pathNode)
            Next
    
            For j As Integer = 0 To filecount - 1
                TreeView1.Nodes.Add(file(j).Name)
            Next
        End Sub
        Private Function GetMultiNode(ByVal treeNode As TreeNode, ByVal path As String) As Boolean
            If Directory.Exists(path) = False Then
                Return False
            End If
    
            Dim dirs As DirectoryInfo = New DirectoryInfo(path)
            Dim dir As DirectoryInfo() = dirs.GetDirectories()
            Dim file As FileInfo() = dirs.GetFiles()
            Dim dircount As Integer = dir.Count()
            Dim filecount As Integer = file.Count()
            Dim sumcount As Integer = dircount + filecount
    
            If sumcount = 0 Then
                Return False
            End If
    
            For j As Integer = 0 To dircount - 1
                treeNode.Nodes.Add(dir(j).Name)
                Dim pathNodeB As String = path & "\" & dir(j).Name
                GetMultiNode(treeNode.Nodes(j), pathNodeB)
            Next
    
            For j As Integer = 0 To filecount - 1
                treeNode.Nodes.Add(file(j).Name)
            Next
    
            Return True
        End Function
    
        Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
    
    
    
    
            ListView1.Clear()
            ListView1.View = View.Details
            ListView1.LabelEdit = True
            ListView1.AllowColumnReorder = True
            ListView1.CheckBoxes = False
            ListView1.FullRowSelect = True
            ListView1.GridLines = True
            ListView1.Sorting = SortOrder.Ascending
            ListView1.Columns.Add("Description", 60, HorizontalAlignment.Left)
            ListView1.Columns.Add("DateTime", 100, HorizontalAlignment.Left)
            ListView1.Columns.Add("Link", -2, HorizontalAlignment.Left)
    
    
            If TreeView1.SelectedNode.Nodes.Count > 0 Then
                For Each node As TreeNode In TreeView1.Nodes
                    node.Collapse()
                Next
                e.Node.Expand()
                For Each a In TreeView1.SelectedNode.Nodes
                    Dim f1 As String = a.fullpath
                    Dim nume1 As String = Path.GetFileName(f1)
                    Dim items1 As ListViewItem = New ListViewItem(nume1)
                    Dim vlist11 As ListViewItem.ListViewSubItem = New ListViewItem.ListViewSubItem()
                    Dim f2 As FileInfo = New FileInfo(fullPath & "\" & nume1)
                    vlist11.Text = f2.CreationTime.ToString
                    items1.SubItems.Add(vlist11)
                    ListView1.Items.Add(items1)
                Next
            Else
                Dim f As String = TreeView1.SelectedNode.FullPath
                Dim nume As String = Path.GetFileName(f)
                Dim items As ListViewItem = New ListViewItem(nume)
                Dim vlist1 As ListViewItem.ListViewSubItem = New ListViewItem.ListViewSubItem()
                Dim fl As FileInfo = New FileInfo(fullPath & "\" & nume)
                vlist1.Text = fl.CreationTime.ToString
                items.SubItems.Add(vlist1)
                ListView1.Items.Add(items)
            End If
    
        End Sub
    
        Private Sub TreeView1_MouseClick(sender As Object, e As MouseEventArgs) Handles TreeView1.MouseClick
    
        End Sub
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, November 8, 2018 10:00 AM
  • You can use a NameSpaceTreeControl (SHCONTF_FOLDERS to not display files)

    + a ListView to display files

    The result is like this on Windows 10 =>


    • Edited by Castorix31 Thursday, November 8, 2018 3:06 PM
    Thursday, November 8, 2018 3:05 PM
  • You can use a NameSpaceTreeControl (SHCONTF_FOLDERS to not display files)

    + a ListView to display files

    The result is like this on Windows 10 =>


    @Castorix31

    Care to post the code that produced the Image.

    Seems there is *very* limited information available concerning NameSpaceTreeControl, and, as far as I can tell, no sample code (other than in an SDK which I can't get to work)


    Regards Les, Livingston, Scotland

    Thursday, November 8, 2018 4:04 PM
  • @Castorix31

    Care to post the code that produced the Image.

    The test I did =>

    (it should be done with INameSpaceTreeControlEvents

     but it crashed on my first try, so I used WM_NOTIFY...)

    Option Strict On
    Imports System.Runtime.InteropServices
    
    Public Class Form1
        Public Enum HRESULT As Integer
            S_OK = 0
            S_FALSE = 1
            E_NOINTERFACE = &H80004002
            E_NOTIMPL = &H80004001
            E_FAIL = &H80004005
        End Enum
    
        <StructLayout(LayoutKind.Sequential)>
        Public Structure RECT
            Public Left As Integer
            Public Top As Integer
            Public Right As Integer
            Public Bottom As Integer
        End Structure
    
        Public Enum NSTCSTYLE As Integer
            NSTCS_HASEXPANDOS = &H1
            NSTCS_HASLINES = &H2
            NSTCS_SINGLECLICKEXPAND = &H4
            NSTCS_FULLROWSELECT = &H8
            NSTCS_SPRINGEXPAND = &H10
            NSTCS_HORIZONTALSCROLL = &H20
            NSTCS_ROOTHASEXPANDO = &H40
            NSTCS_SHOWSELECTIONALWAYS = &H80
            NSTCS_NOINFOTIP = &H200
            NSTCS_EVENHEIGHT = &H400
            NSTCS_NOREPLACEOPEN = &H800
            NSTCS_DISABLEDRAGDROP = &H1000
            NSTCS_NOORDERSTREAM = &H2000
            NSTCS_RICHTOOLTIP = &H4000
            NSTCS_BORDER = &H8000
            NSTCS_NOEDITLABELS = &H10000
            NSTCS_TABSTOP = &H20000
            NSTCS_FAVORITESMODE = &H80000
            NSTCS_AUTOHSCROLL = &H100000
            NSTCS_FADEINOUTEXPANDOS = &H200000
            NSTCS_EMPTYTEXT = &H400000
            NSTCS_CHECKBOXES = &H800000
            NSTCS_PARTIALCHECKBOXES = &H1000000
            NSTCS_EXCLUSIONCHECKBOXES = &H2000000
            NSTCS_DIMMEDCHECKBOXES = &H4000000
            NSTCS_NOINDENTCHECKS = &H8000000
            NSTCS_ALLOWJUNCTIONS = &H10000000
            NSTCS_SHOWTABSBUTTON = &H20000000
            NSTCS_SHOWDELETEBUTTON = &H40000000
            NSTCS_SHOWREFRESHBUTTON = &H80000000
        End Enum
    
        Public Enum SHCONTF As Integer
            SHCONTF_CHECKING_FOR_CHILDREN = &H10
            SHCONTF_FOLDERS = &H20
            SHCONTF_NONFOLDERS = &H40
            SHCONTF_INCLUDEHIDDEN = &H80
            SHCONTF_INIT_ON_FIRST_NEXT = &H100
            SHCONTF_NETPRINTERSRCH = &H200
            SHCONTF_SHAREABLE = &H400
            SHCONTF_STORAGE = &H800
            SHCONTF_NAVIGATION_ENUM = &H1000
            SHCONTF_FASTITEMS = &H2000
            SHCONTF_FLATLIST = &H4000
            SHCONTF_ENABLE_ASYNC = &H8000
            SHCONTF_INCLUDESUPERHIDDEN = &H10000
        End Enum
        Public Enum NSTCROOTSTYLE As Integer
            NSTCRS_VISIBLE = 0
            NSTCRS_HIDDEN = &H1
            NSTCRS_EXPANDED = &H2
        End Enum
        Public Enum NSTCITEMSTATE As Integer
            NSTCIS_NONE = 0
            NSTCIS_SELECTED = &H1
            NSTCIS_EXPANDED = &H2
            NSTCIS_BOLD = &H4
            NSTCIS_DISABLED = &H8
            NSTCIS_SELECTEDNOEXPAND = &H10
        End Enum
    
        Public Enum NSTCGNI As Integer
            NSTCGNI_NEXT = 0
            NSTCGNI_NEXTVISIBLE = 1
            NSTCGNI_PREV = 2
            NSTCGNI_PREVVISIBLE = 3
            NSTCGNI_PARENT = 4
            NSTCGNI_CHILD = 5
            NSTCGNI_FIRSTVISIBLE = 6
            NSTCGNI_LASTVISIBLE = 7
        End Enum
    
        <ComImport>
        <Guid("028212A3-B627-47e9-8856-C14265554E4F")>
        <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
        Public Interface INameSpaceTreeControl
            Function Initialize(hwndParent As IntPtr, ByRef prc As RECT, nsctsFlags As NSTCSTYLE) As HRESULT
            Function TreeAdvise(punk As IntPtr, ByRef pdwCookie As Integer) As HRESULT
            Function TreeUnadvise(pdwCookie As Integer) As HRESULT
            Function AppendRoot(psiRoot As IntPtr, grfEnumFlags As SHCONTF, grfRootStyle As NSTCROOTSTYLE, pif As IntPtr) As HRESULT
            Function InsertRoot(iIndex As Integer, psiRoot As IntPtr, grfEnumFlags As SHCONTF, grfRootStyle As NSTCROOTSTYLE, pif As IntPtr) As HRESULT
            Function RemoveRoot(psiRoot As IntPtr) As HRESULT
            Function RemoveAllRoots() As HRESULT
            Function GetRootItems(ByVal ppsiaRootItems As IntPtr) As HRESULT
            Function SetItemState(psi As IntPtr, nstcisMask As NSTCITEMSTATE, nstcisFlags As NSTCITEMSTATE) As HRESULT
            Function GetItemState(psi As IntPtr, nstcisMask As NSTCITEMSTATE, ByVal pnstcisFlags As NSTCITEMSTATE) As HRESULT
            <PreserveSig()>
            Function GetSelectedItems(ByRef psiaItems As IntPtr) As HRESULT
            Function GetItemCustomState(psi As IntPtr, ByVal piStateNumber As Integer) As HRESULT
            Function SetItemCustomState(psi As IntPtr, iStateNumber As Integer) As HRESULT
            Function EnsureItemVisible(psi As IntPtr) As HRESULT
            Function SetTheme(pszTheme As String) As HRESULT
            Function GetNextItem(psi As IntPtr, nstcgi As NSTCGNI, ByVal ppsiNext As IntPtr) As HRESULT
            Function HitTest(ppt As Point, nstcgi As NSTCGNI, ByVal ppsiOut As IntPtr) As HRESULT
            Function GetItemRect(psi As IntPtr, ByRef prect As RECT) As HRESULT
            Function CollapseAll() As HRESULT
        End Interface
    
        Enum SIGDN As Integer
            SIGDN_NORMALDISPLAY = &H0
            SIGDN_PARENTRELATIVEPARSING = &H80018001
            SIGDN_DESKTOPABSOLUTEPARSING = &H80028000
            SIGDN_PARENTRELATIVEEDITING = &H80031001
            SIGDN_DESKTOPABSOLUTEEDITING = &H8004C000
            SIGDN_FILESYSPATH = &H80058000
            SIGDN_URL = &H80068000
            SIGDN_PARENTRELATIVEFORADDRESSBAR = &H8007C001
            SIGDN_PARENTRELATIVE = &H80080001
        End Enum
    
        <StructLayout(LayoutKind.Sequential)>
        Public Structure PROPARRAY
            Public cElems As UInteger
            Public pElems As IntPtr
        End Structure
    
        <StructLayout(LayoutKind.Explicit, Pack:=1)>
        Public Structure PROPVARIANT
            <FieldOffset(0)>
            Public varType As System.UInt16
            <FieldOffset(2)>
            Public wReserved1 As System.UInt16
            <FieldOffset(4)>
            Public wReserved2 As System.UInt16
            <FieldOffset(6)>
            Public wReserved3 As System.UInt16
            <FieldOffset(8)>
            Public bVal As Byte
            <FieldOffset(8)>
            Public cVal As System.SByte
            <FieldOffset(8)>
            Public uiVal As System.UInt16
            <FieldOffset(8)>
            Public iVal As Short
            <FieldOffset(8)>
            Public uintVal As UInt32
            <FieldOffset(8)>
            Public intVal As Int32
            <FieldOffset(8)>
            Public ulVal As UInt64
            <FieldOffset(8)>
            Public lVal As Int64
            <FieldOffset(8)>
            Public fltVal As Single
            <FieldOffset(8)>
            Public dblVal As Double
            <FieldOffset(8)>
            Public boolVal As Short
            <FieldOffset(8)>
            Public pclsidVal As IntPtr
            ' GUID ID pointer
            <FieldOffset(8)>
            Public pszVal As IntPtr
            ' Ansi string pointer
            <FieldOffset(8)>
            Public pwszVal As IntPtr
            ' Unicode string pointer
            <FieldOffset(8)>
            Public punkVal As IntPtr
            ' punkVal (interface pointer)
            <FieldOffset(8)>
            Public ca As PROPARRAY
            <FieldOffset(8)>
            Public filetime As System.Runtime.InteropServices.ComTypes.FILETIME
        End Structure
    
        <ComImport()>
        <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
        <Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")>
        Public Interface IShellItem
            <PreserveSig()>
            Function BindToHandler(ByVal pbc As IntPtr, ByRef bhid As Guid, ByRef riid As Guid, ByRef ppv As IntPtr) As HRESULT
            Function GetParent(ByRef ppsi As IShellItem) As HRESULT
            Function GetDisplayName(ByVal sigdnName As SIGDN, ByRef ppszName As System.Text.StringBuilder) As HRESULT
            Function GetAttributes(ByVal sfgaoMask As UInteger, ByRef psfgaoAttribs As UInteger) As HRESULT
            Function Compare(ByVal psi As IShellItem, ByVal hint As UInteger, ByRef piOrder As Integer) As HRESULT
        End Interface
    
        <ComImport, Guid("7e9fb0d3-919f-4307-ab2e-9b1860310c93"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
        Friend Interface IShellItem2
            Inherits IShellItem
            '#Region IShellItem
            <PreserveSig()>
            Overloads Function BindToHandler(ByVal pbc As IntPtr, ByRef bhid As Guid, ByRef riid As Guid, ByRef ppv As IntPtr) As HRESULT
            Overloads Function GetParent(ByRef ppsi As IShellItem) As HRESULT
            Overloads Function GetDisplayName(ByVal sigdnName As SIGDN, ByRef ppszName As System.Text.StringBuilder) As HRESULT
            Overloads Function GetAttributes(ByVal sfgaoMask As UInteger, ByRef psfgaoAttribs As UInteger) As HRESULT
            Overloads Function Compare(ByVal psi As IShellItem, ByVal hint As UInteger, ByRef piOrder As Integer) As HRESULT
            '#End Region
    
            'Function GetPropertyStore(<[In]()> ByVal Flags As GETPROPERTYSTOREFLAGS, <[In]()> ByRef riid As Guid, <Out(), MarshalAs(UnmanagedType.Interface)> ByVal ppv As IPropertyStore) As HRESULT
            Function GetPropertyStore(<[In]()> ByVal Flags As GETPROPERTYSTOREFLAGS, <[In]()> ByRef riid As Guid, ByRef ppv As IntPtr) As HRESULT
            Function GetPropertyStoreWithCreateObject(<[In]()> ByVal Flags As GETPROPERTYSTOREFLAGS, <[In](), MarshalAs(UnmanagedType.IUnknown)> ByVal punkCreateObject As Object, <[In]()> ByRef riid As Guid, <Out()> ByRef ppv As IntPtr) As HRESULT
            'Function GetPropertyStoreForKeys(<[In]()> ByRef rgKeys As REFPROPERTYKEY, <[In]()> ByVal cKeys As UInteger, <[In]()> ByVal Flags As GETPROPERTYSTOREFLAGS, <[In]()> ByRef riid As Guid, <Out(), MarshalAs(UnmanagedType.IUnknown)> ByVal ppv As IPropertyStore) As HRESULT
            Function GetPropertyStoreForKeys(<[In]()> ByRef rgKeys As REFPROPERTYKEY, <[In]()> ByVal cKeys As UInteger, <[In]()> ByVal Flags As GETPROPERTYSTOREFLAGS, <[In]()> ByRef riid As Guid, ByRef ppv As IntPtr) As HRESULT
            Function GetPropertyDescriptionList(<[In]()> ByRef keyType As REFPROPERTYKEY, <[In]()> ByRef riid As Guid, <Out()> ByRef ppv As IntPtr) As HRESULT
            'Function Update(<[In](), MarshalAs(UnmanagedType.Interface)> ByVal pbc As IBindCtx) As HRESULT
            Function Update(<[In](), MarshalAs(UnmanagedType.Interface)> ByVal pbc As IntPtr) As HRESULT
            Function GetProperty(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef ppropvar As PROPVARIANT) As HRESULT
            Function GetCLSID(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef pclsid As Guid) As HRESULT
    
            <PreserveSig>
            Function GetFileTime(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef pft As System.Runtime.InteropServices.ComTypes.FILETIME) As HRESULT
            Function GetInt32(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef pi As Integer) As HRESULT
            Function GetString(<[In]()> ByRef key As REFPROPERTYKEY, <Out(), MarshalAs(UnmanagedType.LPWStr)> ByRef ppsz As String) As HRESULT
            Function GetUInt32(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef pui As UInteger) As HRESULT
            Function GetUInt64(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef pull As ULong) As HRESULT
            Function GetBool(<[In]()> ByRef key As REFPROPERTYKEY, <Out()> ByRef pf As Integer) As HRESULT
        End Interface
    
        Public Enum GETPROPERTYSTOREFLAGS
            GPS_DEFAULT = 0
            GPS_HANDLERPROPERTIESONLY = &H1
            GPS_READWRITE = &H2
            GPS_TEMPORARY = &H4
            GPS_FASTPROPERTIESONLY = &H8
            GPS_OPENSLOWITEM = &H10
            GPS_DELAYCREATION = &H20
            GPS_BESTEFFORT = &H40
            GPS_NO_OPLOCK = &H80
            GPS_PREFERQUERYPROPERTIES = &H100
            GPS_EXTRINSICPROPERTIES = &H200
            GPS_EXTRINSICPROPERTIESONLY = &H400
            GPS_MASK_VALID = &H7FF
        End Enum
    
        <StructLayout(LayoutKind.Sequential, Pack:=4)>
        Public Structure REFPROPERTYKEY
            Private fmtid As Guid
            Private pid As Integer
            Public ReadOnly Property FormatId() As Guid
                Get
                    Return Me.fmtid
                End Get
            End Property
            Public ReadOnly Property PropertyId() As Integer
                Get
                    Return Me.pid
                End Get
            End Property
            Public Sub New(ByVal formatId As Guid, ByVal propertyId As Integer)
                Me.fmtid = formatId
                Me.pid = propertyId
            End Sub
            Public Shared ReadOnly PKEY_DateCreated As REFPROPERTYKEY = New REFPROPERTYKEY(New Guid("B725F130-47EF-101A-A5F1-02608C9EEBAC"), 15)
        End Structure
    
        Public Enum SIATTRIBFLAGS
            SIATTRIBFLAGS_AND = &H1
            SIATTRIBFLAGS_OR = &H2
            SIATTRIBFLAGS_APPCOMPAT = &H3
            SIATTRIBFLAGS_MASK = &H3
            SIATTRIBFLAGS_ALLITEMS = &H4000
        End Enum
    
        Public Const DROPEFFECT_NONE = 0
        Public Const DROPEFFECT_COPY = 1
        Public Const DROPEFFECT_MOVE = 2
        Public Const DROPEFFECT_LINK = 4
    
        Public Const SFGAO_CANCOPY = DROPEFFECT_COPY ' Objects can be copied    (= &H1)
        Public Const SFGAO_CANMOVE = DROPEFFECT_MOVE ' Objects can be moved     (= &H2)
        Public Const SFGAO_CANLINK = DROPEFFECT_LINK ' Objects can be linked    (= &H4)
        Public Const SFGAO_STORAGE = &H8L     ' supports BindToObject(IID_IStorage)
        Public Const SFGAO_CANRENAME = &H10L     ' Objects can be renamed
        Public Const SFGAO_CANDELETE = &H20L     ' Objects can be deleted
        Public Const SFGAO_HASPROPSHEET = &H40L     ' Objects have property sheets
        Public Const SFGAO_DROPTARGET = &H100L     ' Objects are drop target
        Public Const SFGAO_CAPABILITYMASK = &H177L
        Public Const SFGAO_SYSTEM = &H1000L     ' System object
        Public Const SFGAO_ENCRYPTED = &H2000L     ' Object is encrypted (use alt color)
        Public Const SFGAO_ISSLOW = &H4000L     ' 'Slow' object
        Public Const SFGAO_GHOSTED = &H8000L     ' Ghosted icon
        Public Const SFGAO_LINK = &H10000L     ' Shortcut (link)
        Public Const SFGAO_SHARE = &H20000L     ' Shared
        Public Const SFGAO_READONLY = &H40000L     ' Read-only
        Public Const SFGAO_HIDDEN = &H80000L     ' Hidden object
        Public Const SFGAO_DISPLAYATTRMASK = &HFC000L
        Public Const SFGAO_FILESYSANCESTOR = &H10000000L     ' May contain children with SFGAO_FILESYSTEM
        Public Const SFGAO_FOLDER = &H20000000L     ' Support BindToObject(IID_IShellFolder)
        Public Const SFGAO_FILESYSTEM = &H40000000L     ' Is a win32 file system object (file/folder/root)
        Public Const SFGAO_HASSUBFOLDER = &H80000000L     ' May contain children with SFGAO_FOLDER (may be slow)
        Public Const SFGAO_CONTENTSMASK = &H80000000L
        Public Const SFGAO_VALIDATE = &H1000000L     ' Invalidate cached information (may be slow)
        Public Const SFGAO_REMOVABLE = &H2000000L     ' Is this removeable media?
        Public Const SFGAO_COMPRESSED = &H4000000L     ' Object is compressed (use alt color)
        Public Const SFGAO_BROWSABLE = &H8000000L     ' Supports IShellFolder, but only implements CreateViewObject() (non-folder view)
        Public Const SFGAO_NONENUMERATED = &H100000L     ' Is a non-enumerated object (should be hidden)
        Public Const SFGAO_NEWCONTENT = &H200000L     ' Should show bold in explorer tree
        Public Const SFGAO_CANMONIKER = &H400000L     ' Obsolete
        Public Const SFGAO_HASSTORAGE = &H400000L     ' Obsolete
        Public Const SFGAO_STREAM = &H400000L     ' Supports BindToObject(IID_IStream)
        Public Const SFGAO_STORAGEANCESTOR = &H800000L     ' May contain children with SFGAO_STORAGE or SFGAO_STREAM
        Public Const SFGAO_STORAGECAPMASK = &H70C50008L     ' For determining storage capabilities, ie for open/save semantics
        Public Const SFGAO_PKEYSFGAOMASK = &H81044000L     ' Attributes that are masked out for PKEY_SFGAOFlags because they are considered to cause slow calculations or lack context (SFGAO_VALIDATE | SFGAO_ISSLOW | SFGAO_HASSUBFOLDER and others)
    
        <ComImport()>
        <InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
        <Guid("b63ea76d-1f85-456f-a19c-48159efa858b")>
        Public Interface IShellItemArray
            'Function BindToHandler(pbc As IBindCtx, ByRef bhid As Guid, ByRef riid As Guid, ByRef ppvOut As IntPtr) As HRESULT
            Function BindToHandler(pbc As IntPtr, ByRef bhid As Guid, ByRef riid As Guid, ByRef ppvOut As IntPtr) As HRESULT
            Function GetPropertyStore(flags As GETPROPERTYSTOREFLAGS, ByRef riid As Guid, ByRef ppv As IntPtr) As HRESULT
            Function GetPropertyDescriptionList(keyType As REFPROPERTYKEY, ByRef riid As Guid, ByRef ppv As IntPtr) As HRESULT
            'Function GetAttributes(AttribFlags As SIATTRIBFLAGS, sfgaoMask As SFGAOF, ByRef psfgaoAttribs As SFGAOF) As HRESULT
            Function GetAttributes(AttribFlags As SIATTRIBFLAGS, sfgaoMask As Integer, ByRef psfgaoAttribs As Integer) As HRESULT
            Function GetCount(ByRef pdwNumItems As Integer) As HRESULT
            Function GetItemAt(dwIndex As Integer, ByRef ppsi As IShellItem) As HRESULT
            'Function EnumItems(ByRef ppenumShellItems As IEnumShellItems) As HRESULT
            Function EnumItems(ByRef ppenumShellItems As IntPtr) As HRESULT
        End Interface
    
        <ComImport(),
        InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
        Guid("70629033-e363-4a28-a567-0db78006e6d7")>
        Public Interface IEnumShellItems
            <PreserveSig()>
            Function [Next](ByVal celt As UInteger, ByRef rgelt As IShellItem, ByRef pceltFetched As UInteger) As HRESULT
            Function Skip(ByVal celt As UInteger) As HRESULT
            Function Reset() As HRESULT
            Function Clone(ByRef ppenum As IEnumShellItems) As HRESULT
        End Interface
    
    
        Public CSIDL_DESKTOP As Integer = 0
    
        <DllImport("Shell32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function SHGetFolderLocation(ByVal hwndOwner As IntPtr, ByVal nFolder As Integer, ByVal hToken As IntPtr, ByVal dwReserved As UInteger, <Out> ByRef ppidl As IntPtr) As HRESULT
        End Function
    
        <DllImport("Shell32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function SHCreateItemFromIDList(ByVal pidl As IntPtr, <[In], MarshalAs(UnmanagedType.LPStruct)> ByVal riid As Guid, <Out> ByRef ppv As IntPtr) As HRESULT
        End Function
    
        <DllImport("User32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function MoveWindow(hWnd As IntPtr, X As Integer, Y As Integer, nWidth As Integer, nHeight As Integer, bRepaint As Boolean) As Boolean
        End Function
    
        <DllImport("User32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function FindWindowEx(ByVal hWndParent As IntPtr, ByVal hWndChildAfter As IntPtr, ByVal lpszClass As String, ByVal lpszWindow As String) As IntPtr
        End Function
    
        <DllImport("Ole32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function OleInitialize(pvReserved As IntPtr) As HRESULT
        End Function
    
        <DllImport("Kernel32.dll", CharSet:=CharSet.Auto)>
        Public Shared Function Beep(dwFreq As UInteger, dwDuration As UInteger) As Boolean
        End Function
    
        <StructLayout(LayoutKind.Sequential)>
        Structure SYSTEMTIME
            Public wYear As UShort
            Public wMonth As UShort
            Public wDayOfWeek As UShort
            Public wDay As UShort
            Public wHour As UShort
            Public wMinute As UShort
            Public wSecond As UShort
            Public wMilliseconds As UShort
        End Structure
    
        <DllImport("Kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function FileTimeToSystemTime(<[In]()> ByRef lpFileTime As System.Runtime.InteropServices.ComTypes.FILETIME, <Out()> ByRef lpSystemTime As SYSTEMTIME) As Boolean
        End Function
    
        <DllImport("Kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
        Public Shared Function FileTimeToLocalFileTime(<[In]()> ByRef lpFileTime As System.Runtime.InteropServices.ComTypes.FILETIME, <Out()> ByRef lpLocalFileTime As System.Runtime.InteropServices.ComTypes.FILETIME) As Boolean
        End Function
    
        Dim pNameSpaceTreeControl As INameSpaceTreeControl
        Dim ListView1 As ListView
        Dim PictureBox1 As PictureBox
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Me.PictureBox1 = New PictureBox()
            Me.PictureBox1.Location = New System.Drawing.Point(20, 20)
            Me.PictureBox1.Name = "PictureBox1"
            Me.PictureBox1.Size = New System.Drawing.Size(300, 400)
            Me.PictureBox1.TabIndex = 0
            Me.PictureBox1.TabStop = False
            Me.PictureBox1.BorderStyle = BorderStyle.FixedSingle
            Me.Controls.Add(Me.PictureBox1)
    
            OleInitialize(IntPtr.Zero)
            Dim CLSID_NamespaceTreeControl As New Guid("AE054212-3535-4430-83ED-D501AA6680E6")
            Dim NameSpaceTreeControlType As Type = Type.GetTypeFromCLSID(CLSID_NamespaceTreeControl, True)
            Dim NameSpaceTreeControl As Object = Activator.CreateInstance(NameSpaceTreeControlType)
            pNameSpaceTreeControl = DirectCast(NameSpaceTreeControl, INameSpaceTreeControl)
            Dim hr As HRESULT = pNameSpaceTreeControl.Initialize(PictureBox1.Handle, Nothing, NSTCSTYLE.NSTCS_RICHTOOLTIP Or NSTCSTYLE.NSTCS_FAVORITESMODE Or NSTCSTYLE.NSTCS_FULLROWSELECT Or NSTCSTYLE.NSTCS_NOREPLACEOPEN Or NSTCSTYLE.NSTCS_AUTOHSCROLL Or NSTCSTYLE.NSTCS_HASEXPANDOS Or NSTCSTYLE.NSTCS_HASLINES)
            If (hr = HRESULT.S_OK) Then
                Dim pidl As IntPtr = IntPtr.Zero
                hr = SHGetFolderLocation(IntPtr.Zero, CSIDL_DESKTOP, IntPtr.Zero, 0, pidl)
                If (hr = HRESULT.S_OK) Then
                    Dim psi As IntPtr = IntPtr.Zero
                    Dim GUID_IShellItem As New Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")
                    hr = SHCreateItemFromIDList(pidl, GUID_IShellItem, psi)
                    If (hr = HRESULT.S_OK) Then
                        'hr = pNameSpaceTreeControl.AppendRoot(psi, SHCONTF.SHCONTF_FOLDERS Or SHCONTF.SHCONTF_NONFOLDERS, NSTCROOTSTYLE.NSTCRS_EXPANDED, IntPtr.Zero)
                        hr = pNameSpaceTreeControl.AppendRoot(psi, SHCONTF.SHCONTF_FOLDERS, NSTCROOTSTYLE.NSTCRS_EXPANDED, IntPtr.Zero)
                        If (hr = HRESULT.S_OK) Then
    
                        End If
                    End If
                End If
            End If
            Dim hWndTree As IntPtr = FindWindowEx(PictureBox1.Handle, IntPtr.Zero, "NameSpaceTreeControl", Nothing)
            MoveWindow(hWndTree, 0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height, True)
    
            m_NewSubClassDelegate = AddressOf NewSubClassProc
            SetWindowSubclass(hWndTree, m_NewSubClassDelegate, 0, 0)
    
            ListView1 = New ListView()
            ListView1.Location = New Point(340, 20)
            ListView1.Size = New Size(320, 400)
            ListView1.View = View.Details
            ListView1.Columns.Add("Name", 200, HorizontalAlignment.Left)
            ListView1.Columns.Add("Date", 100, HorizontalAlignment.Center)
            Me.Controls.Add(ListView1)
    
            Me.ClientSize = New Size(680, 440)
            CenterToScreen()
        End Sub
    
        Private Shared m_NewSubClassDelegate As SUBCLASSPROC
    
        Public Delegate Function SUBCLASSPROC(hWnd As IntPtr, uMsg As UInteger, wParam As IntPtr, lParam As IntPtr, uIdSubclass As IntPtr, dwRefData As UInteger) As Integer
    
        <DllImport("comctl32.dll", EntryPoint:="SetWindowSubclass")>
        Public Shared Function SetWindowSubclass(hWnd As IntPtr, pfnSubclass As SUBCLASSPROC, uIdSubclass As UInteger, dwRefData As UInteger) As Boolean
        End Function
    
        <DllImport("comctl32.dll", EntryPoint:="DefSubclassProc")>
        Public Shared Function DefSubclassProc(hWnd As IntPtr, uMsg As UInteger, wParam As IntPtr, lParam As IntPtr) As Integer
        End Function
    
        Public Const WM_NOTIFY = &H4E
        Public Const TVN_FIRST = (0 - 400)
        Public Const TVN_SELCHANGINGW = (TVN_FIRST - 50)
        Public Const TVN_SELCHANGEDW = (TVN_FIRST - 51)
    
        <StructLayout(LayoutKind.Sequential)>
        Public Structure NMHDR
            Public hwndFrom As IntPtr
            Public idFrom As UInt32
            Public code As Integer
        End Structure
    
        Private Shared Function NewSubClassProc(hWnd As IntPtr, uMsg As UInteger, wParam As IntPtr, lParam As IntPtr, uIdSubclass As IntPtr, dwRefData As UInteger) As Integer
            Select Case uMsg
                Case WM_NOTIFY
                    Dim nmhdr As NMHDR = CType(Marshal.PtrToStructure(lParam, GetType(NMHDR)), NMHDR)
                    Select Case nmhdr.code
                        Case TVN_SELCHANGEDW
                            'Beep(4000, 10)
                            Dim pItems As IntPtr = IntPtr.Zero
                            Dim hr As HRESULT = Form1.pNameSpaceTreeControl.GetSelectedItems(pItems)
                            If (hr = HRESULT.S_OK) Then
                                Form1.ListView1.Items.Clear()
                                Dim pShellItemArray As IShellItemArray = CType(Marshal.GetObjectForIUnknown(pItems), IShellItemArray)
                                'Dim cCount As Integer
                                'hr = pShellItemArray.GetCount(cCount)
                                Dim psiSelected As IShellItem = Nothing
                                hr = pShellItemArray.GetItemAt(0, psiSelected)
                                Dim BHID_EnumItems As New Guid("94f60519-2850-4924-aa5a-d15e84868039")
                                'Dim IID_IEnumShellItems As New Guid("70629033-E363-4A28-A567-0DB78006E6D7")
                                If (hr = HRESULT.S_OK) Then
                                    Dim sbItemName As Text.StringBuilder = New Text.StringBuilder(260)
                                    hr = psiSelected.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY, sbItemName)
                                    Dim pEnumShellItems As IEnumShellItems = Nothing
                                    Dim pEnum As IntPtr
                                    hr = psiSelected.BindToHandler(IntPtr.Zero, BHID_EnumItems, GetType(IEnumShellItems).GUID, pEnum)
                                    If (hr = HRESULT.S_OK) Then
                                        pEnumShellItems = CType(Marshal.GetObjectForIUnknown(pEnum), IEnumShellItems)
                                        Dim psi As IShellItem = Nothing
                                        Dim nFetched As UInteger = 0
                                        Dim pszName As IntPtr = IntPtr.Zero
                                        While ((HRESULT.S_OK = pEnumShellItems.Next(1, psi, nFetched)) AndAlso (nFetched = 1))
                                            Dim sbDisplayName As Text.StringBuilder = New Text.StringBuilder(260)
                                            hr = psi.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY, sbDisplayName)
                                            If (hr = HRESULT.S_OK) Then
                                                'Console.WriteLine(String.Format("" & vbTab & "Item Name : {0}", sbDisplayName.ToString()))
                                                Dim nAttributes As UInteger = 0
                                                hr = psi.GetAttributes(SFGAO_FOLDER Or SFGAO_FILESYSTEM, nAttributes)
                                                Dim isDirectory As Boolean = (nAttributes And SFGAO_FOLDER) <> 0
                                                Dim isFileSystem As Boolean = (nAttributes And SFGAO_FILESYSTEM) <> 0
                                                If (Not (isDirectory) And isFileSystem) Then
                                                    Dim sItem(2) As String
                                                    Dim lvi As ListViewItem
                                                    sItem(0) = sbDisplayName.ToString()
    
                                                    Dim psi2 As IShellItem2 = Nothing
                                                    psi2 = CType(psi, IShellItem2)
                                                    Dim ft As System.Runtime.InteropServices.ComTypes.FILETIME = Nothing
                                                    Dim ftlocal As System.Runtime.InteropServices.ComTypes.FILETIME = Nothing
                                                    Dim pk As REFPROPERTYKEY = REFPROPERTYKEY.PKEY_DateCreated
                                                    hr = psi2.GetFileTime(pk, ft)
                                                    Dim st As SYSTEMTIME = New SYSTEMTIME
                                                    FileTimeToLocalFileTime(ft, ftlocal)
                                                    FileTimeToSystemTime(ftlocal, st)
    
                                                    sItem(1) = String.Format("{0:d4}/{1:d2}/{2:d2} {3:d2}:{4:d2}", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute)
                                                    lvi = New ListViewItem(sItem)
                                                    Form1.ListView1.Items.Add(lvi)
                                                End If
                                            End If
                                        End While
                                        If (psi IsNot Nothing) Then
                                            Marshal.ReleaseComObject(psi)
                                        End If
                                        Marshal.Release(pEnum)
                                    End If
                                End If
                                Marshal.Release(pItems)
                            End If
                    End Select
            End Select
            Return DefSubclassProc(hWnd, uMsg, wParam, lParam)
        End Function
    End Class
    
    
    

    Thursday, November 8, 2018 4:19 PM
  • @Castorix31

    Care to post the code that produced the Image.

    The test I did =>

    (it should be done with INameSpaceTreeControlEvents

     but it crashed on my first try, so I used WM_NOTIFY...)

    Hi

    Thanks, got it working. Lots there to study - doubt if I can concentrate that much :)


    Regards Les, Livingston, Scotland

    Thursday, November 8, 2018 4:38 PM