Guest User

Windows TreeView Control

a guest
Jan 23rd, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 32.39 KB | None | 0 0
  1. Imports System.ComponentModel
  2. Imports System.IO
  3. Imports System.Runtime.InteropServices
  4.  
  5. ''' <summary>
  6. ''' Windows Tree View Control 1.0.0
  7. ''' Created by Eprouvez
  8. ''' Credits To Perry (http://glassocean.net/how-to-create-a-treeview-file-browser-component-in-vb-net/)
  9. ''' </summary>
  10. Public Class WindowsTreeView
  11.     Inherits TreeView
  12.  
  13.     Private MyComputerIcon As String = KnownFolders.GetPath(KnownFolders.KnownFolder.SystemX86) & "\shell32.dll,15"
  14.     Private RootNode As TreeNode
  15.  
  16.     Private _ImageList As New ImageList
  17.  
  18.     Public Sub New()
  19.         'SetStyle(ControlStyles.DoubleBuffer, True)
  20.  
  21.         ImageList = _ImageList
  22.         Font = New Font("Segoe UI", 8.25)
  23.         'FullRowSelect = True
  24.  
  25.         Nodes.Clear()
  26.  
  27.  
  28.         If Not LicenseManager.UsageMode = LicenseUsageMode.Designtime Then
  29.  
  30.             Try
  31.                 CacheIndexedIcon(New EmbeddedIconInfo(MyComputerIcon), "This PC")
  32.  
  33.             Catch ex As Exception
  34.                 CacheBlankIcon("This PC")
  35.             End Try
  36.  
  37.             CacheBlankIcon("blank")
  38.  
  39.             RootNode = Me.Nodes.Add("This PC", "This PC", "This PC", "This PC")
  40.  
  41.             RefreshFolders()
  42.         End If
  43.  
  44.     End Sub
  45.  
  46. #Region " Routines & Functions "
  47.  
  48.     ''' <summary>
  49.     ''' Refreshes all files and folders
  50.     ''' </summary>
  51.     Sub RefreshFolders()
  52.  
  53.         RootNode.Nodes.Clear()
  54.  
  55.         Me.BeginUpdate()
  56.  
  57.         For Each SpecialFolder As String In ThisPCDefault()
  58.             Dim Node As New TreeNode(SpecialFolder.Substring(SpecialFolder.LastIndexOf("\") + 1))
  59.  
  60.             Node.Tag = SpecialFolder
  61.             Node.ImageKey = CacheIcon(SpecialFolder, SpecialFolder)
  62.             Node.SelectedImageKey = Node.ImageKey
  63.  
  64.             Node.Nodes.Add("*DUMMY*")
  65.             RootNode.Nodes.Add(Node)
  66.         Next
  67.  
  68.         For Each Drive In DriveInfo.GetDrives
  69.             If Drive.DriveType = DriveType.Fixed Or DriveType.Removable Or DriveType.CDRom Then
  70.                 Dim Node As New TreeNode
  71.  
  72.                 If Drive.IsReady Then
  73.                     If Drive.Name = Path.GetPathRoot(Environment.SystemDirectory) AndAlso Drive.VolumeLabel = "" Then
  74.                         Node.Text = "Local Disk (" & Drive.Name.Replace("\", ")")
  75.                     Else
  76.                         Node.Text = Drive.VolumeLabel & " (" & Drive.Name.Replace("\", ")")
  77.                     End If
  78.                     Node.Nodes.Add("*DUMMY*")
  79.                 ElseIf Drive.DriveType = DriveType.CDRom Then
  80.                     Node.Text = "CD Drive (" & Drive.Name.Replace("\", ")")
  81.                 Else
  82.                     Node.Text = Drive.Name
  83.                     Node.Nodes.Add("*DUMMY*")
  84.                 End If
  85.  
  86.                 Node.Tag = Drive.RootDirectory
  87.                 Node.ImageKey = CacheIcon(Drive.RootDirectory.Name, Drive.Name)
  88.                 Node.SelectedImageKey = Node.ImageKey
  89.  
  90.                 RootNode.Nodes.Add(Node)
  91.  
  92.             End If
  93.  
  94.         Next
  95.  
  96.         Me.EndUpdate()
  97.         RootNode.Expand()
  98.  
  99.  
  100.     End Sub
  101.  
  102.     Private Function ThisPCDefault() As String()
  103.  
  104.         Dim Paths As New List(Of String)
  105.  
  106.         With Paths
  107.             .Add(KnownFolders.GetPath(KnownFolders.KnownFolder.Desktop))
  108.             .Add(KnownFolders.GetPath(KnownFolders.KnownFolder.Documents))
  109.             .Add(KnownFolders.GetPath(KnownFolders.KnownFolder.Downloads))
  110.             .Add(KnownFolders.GetPath(KnownFolders.KnownFolder.Music))
  111.             .Add(KnownFolders.GetPath(KnownFolders.KnownFolder.Pictures))
  112.             .Add(KnownFolders.GetPath(KnownFolders.KnownFolder.Videos))
  113.         End With
  114.  
  115.         Return Paths.ToArray
  116.  
  117.     End Function
  118.  
  119. #End Region
  120.  
  121. #Region " Overrides "
  122.  
  123.     Protected Overrides Sub WndProc(ByRef m As Message)
  124.         If m.Msg = &H14 AndAlso Not LicenseManager.UsageMode = LicenseUsageMode.Designtime Then
  125.             m.Msg = &H0
  126.         End If
  127.  
  128.         MyBase.WndProc(m)
  129.     End Sub
  130.  
  131.     Protected Overrides Sub OnBeforeExpand(e As TreeViewCancelEventArgs)
  132.         MyBase.BeginUpdate()
  133.  
  134.         If Not e.Node.Text = "This PC" Then
  135.  
  136.             e.Node.Nodes.Clear()
  137.  
  138.             Dim Info As New DirectoryInfo(e.Node.Tag.ToString)
  139.  
  140.             Dim Directories As DirectoryInfo() = Info.GetDirectories
  141.             Dim Files As FileInfo() = Info.GetFiles
  142.  
  143.             For Each Directory As DirectoryInfo In Directories
  144.  
  145.                 Dim Node As New TreeNode(Directory.Name)
  146.                 Dim Extension As String = GetExtension(Directory.FullName)
  147.  
  148.                 Node.Tag = Directory.FullName
  149.                 Node.ImageKey = Extension
  150.                 Node.SelectedImageKey = Node.ImageKey
  151.                 Node.Nodes.Add("*DUMMY*")
  152.  
  153.                 e.Node.Nodes.Add(Node)
  154.  
  155.             Next
  156.  
  157.             CacheIcons(Directories)
  158.  
  159.             If _ShowFiles Then
  160.  
  161.                 For Each File As FileInfo In Files
  162.  
  163.                     Dim Node As New TreeNode(File.Name)
  164.                     Dim Extension As String = GetExtension(File.FullName)
  165.  
  166.                     Node.Tag = File.FullName
  167.                     Node.ImageKey = Extension
  168.                     Node.SelectedImageKey = Node.ImageKey
  169.  
  170.                     e.Node.Nodes.Add(Node)
  171.  
  172.                 Next
  173.  
  174.                 CacheIcons(Files)
  175.  
  176.             End If
  177.  
  178.         End If
  179.  
  180.         MyBase.EndUpdate()
  181.  
  182.         MyBase.OnBeforeExpand(e)
  183.     End Sub
  184.  
  185.     Protected Overrides Sub OnBeforeCollapse(e As TreeViewCancelEventArgs)
  186.  
  187.         Me.BeginUpdate()
  188.  
  189.         If Not e.Node.Text = "This PC" Then
  190.             e.Node.Nodes.Clear()
  191.             e.Node.Nodes.Add("*DUMMY*")
  192.         End If
  193.  
  194.         Me.EndUpdate()
  195.  
  196.         MyBase.OnBeforeCollapse(e)
  197.     End Sub
  198.  
  199. #End Region
  200.  
  201. #Region " Properties "
  202.  
  203.     Private _ShowFiles As Boolean = False
  204.     Public Property ShowFiles() As Boolean
  205.         Get
  206.             Return _ShowFiles
  207.         End Get
  208.         Set(ByVal value As Boolean)
  209.             _ShowFiles = value
  210.             RefreshFolders()
  211.         End Set
  212.     End Property
  213.  
  214. #End Region
  215.  
  216. #Region " Extract Indexed Icon "
  217.  
  218.     Declare Function ExtractIcon Lib "shell32.dll" Alias "ExtractIconA" (Handle As Integer, FileName As String, Index As Integer) As IntPtr
  219.     Declare Function ExtractIconEx Lib "shell32.dll" Alias "ExtractIconExA" (ByVal FileName As String, ByVal Index As Integer, ByVal LargeSet() As IntPtr, ByVal SmallSet() As IntPtr, ByVal nIcons As Integer) As Integer
  220.     Declare Function DestroyIcon Lib "user32.dll" (ByVal hIcon As Integer) As Integer
  221.  
  222.     Function ExtractIconFromFile(ByVal IconInfo As EmbeddedIconInfo) As Icon
  223.         Return ExtractIconFromFile(IconInfo.FileName, IconInfo.IconIndex)
  224.     End Function
  225.  
  226.     Function ExtractIconFromFile(ByVal File As String, Optional Index As Integer = 0) As Icon
  227.         If Not IO.File.Exists(File) Then Return Nothing
  228.  
  229.         Dim Handle As IntPtr() = New IntPtr(0) {IntPtr.Zero}
  230.         Dim Dummy As IntPtr() = New IntPtr(0) {IntPtr.Zero}
  231.  
  232.         Try
  233.             Dim Count = ExtractIconEx(File, Index, Dummy, Handle, 1)
  234.             Dim Icon As Icon = Icon.FromHandle(Handle(0)).Clone
  235.             Return Icon
  236.         Catch ex As Exception
  237.             Return Nothing
  238.         Finally
  239.  
  240.             For Each I As IntPtr In Handle
  241.                 If (Not I.Equals(IntPtr.Zero)) Then
  242.                     DestroyIcon(I)
  243.                 End If
  244.             Next I
  245.  
  246.             For Each I As IntPtr In Dummy
  247.                 If Not (I.Equals(IntPtr.Zero)) Then
  248.                     DestroyIcon(I)
  249.                 End If
  250.             Next I
  251.         End Try
  252.     End Function
  253.  
  254.     Function GetIndexedIconAsImage(ByVal Path As String, Optional Index As Integer = 0) As Image
  255.         Dim Icon As Icon, Image As Image
  256.         Dim Info As New EmbeddedIconInfo(Path, Index)
  257.  
  258.         Try
  259.             Icon = ExtractIconFromFile(Info)
  260.             Image = Icon.ToBitmap
  261.         Catch ex As Exception
  262.             Image = Nothing
  263.         End Try
  264.         Return Image
  265.     End Function
  266.  
  267. #End Region
  268.  
  269. #Region " Extract Icon "
  270.  
  271.     Private _Handles As New List(Of IntPtr)
  272.  
  273.     Function GetIconAsImage(ByVal Path As String) As Image
  274.  
  275.         Dim Icon As Icon, Image As Image
  276.         Dim FileInfo As New IconInfo
  277.  
  278.         FileInfo.Name = New String(Chr(0), 260)
  279.         FileInfo.Type = New String(Chr(0), 80)
  280.  
  281.         SHGetFileInfo(Path, 0, FileInfo, Marshal.SizeOf(FileInfo), IconInfo.Icon Or IconInfo.SmallIcon)
  282.  
  283.         Try
  284.             Icon = Icon.FromHandle(FileInfo.IconHandle).Clone
  285.             Image = Icon.ToBitmap
  286.         Catch ex As Exception
  287.             Image = Nothing
  288.         Finally
  289.             DestroyIcon(FileInfo.IconHandle)
  290.             '_Handles.Add(FileInfo.IconHandle)
  291.         End Try
  292.  
  293.         Return Image
  294.     End Function
  295.  
  296.     Function GetOpenIconAsImage(ByVal Path As String) As Image
  297.  
  298.         Dim Icon As Icon, Image As Image
  299.         Dim FileInfo As New IconInfo
  300.  
  301.         FileInfo.Name = New String(Chr(0), 260)
  302.         FileInfo.Type = New String(Chr(0), 80)
  303.  
  304.         SHGetFileInfo(Path, 0, FileInfo, Marshal.SizeOf(FileInfo), IconInfo.Icon Or IconInfo.SmallIcon Or IconInfo.OpenIcon)
  305.  
  306.         Try
  307.             Icon = Icon.FromHandle(FileInfo.IconHandle).Clone
  308.             Image = Icon.ToBitmap
  309.         Catch ex As Exception
  310.             Image = Nothing
  311.         Finally
  312.             _Handles.Add(FileInfo.IconHandle)
  313.         End Try
  314.  
  315.         Return Image
  316.     End Function
  317.  
  318. #End Region
  319.  
  320. #Region " Icon Information "
  321.  
  322.     Public Declare Auto Function SHGetFileInfo Lib "shell32.dll" (ByVal Path As String, ByVal Attributes As Integer, ByRef Info As IconInfo, ByVal InfoSize As Integer, ByVal Flags As Integer) As IntPtr
  323.  
  324.     Structure IconInfo
  325.  
  326.         Public Const Icon As Integer = &H100
  327.         Public Const SmallIcon As Integer = &H1
  328.         Public Const LargeIcon As Integer = &H0
  329.         Public Const OpenIcon As Integer = &H2
  330.  
  331.         Public IconHandle As IntPtr
  332.         Public Index As Integer
  333.         Public Attributes As Integer
  334.         <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
  335.         Public Name As String
  336.         <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)>
  337.         Public Type As String
  338.     End Structure
  339.  
  340.     Public Structure EmbeddedIconInfo
  341.  
  342.         Sub New(FileParam As String)
  343.             If Not Parse(FileParam) Then Throw New Exception("No index given!")
  344.             Dim Params As String() = FileParam.Split(",")
  345.             _FileName = Params(0)
  346.             _Index = Params(1)
  347.         End Sub
  348.         Sub New(FileName As String, Index As Integer)
  349.             _FileName = FileName
  350.             _Index = Index
  351.         End Sub
  352.  
  353.         Shared Function Parse(File As String) As Boolean
  354.             Return File.Contains(",")
  355.         End Function
  356.  
  357.         Private _FileName As String
  358.         Public Property FileName() As String
  359.             Get
  360.                 Return _FileName
  361.             End Get
  362.             Set(ByVal value As String)
  363.                 _FileName = value
  364.             End Set
  365.         End Property
  366.  
  367.         Private _Index As Integer
  368.         Public Property IconIndex() As Integer
  369.             Get
  370.                 Return _Index
  371.             End Get
  372.             Set(ByVal value As Integer)
  373.                 _Index = value
  374.             End Set
  375.         End Property
  376.  
  377.     End Structure
  378.  
  379.     Shared Function GetEmbeddedIconInfo(Args As String) As EmbeddedIconInfo
  380.  
  381.         Dim Info As New EmbeddedIconInfo()
  382.  
  383.         If [String].IsNullOrEmpty(Args) Then Return Info
  384.  
  385.         Dim FileName As String = [String].Empty
  386.  
  387.         Dim Index As Integer = 0
  388.         Dim StringIndex As String = [String].Empty
  389.  
  390.         Dim Seperate As Integer = Args.IndexOf(",")
  391.  
  392.         If Seperate > 0 Then
  393.             FileName = Args.Substring(0, Seperate)
  394.             StringIndex = Integer.Parse(Args.Substring(Seperate + 1))
  395.         Else
  396.             FileName = Args
  397.         End If
  398.  
  399.         If Not [String].IsNullOrEmpty(StringIndex) Then
  400.  
  401.             Index = Integer.Parse(StringIndex)
  402.             If Index < 0 Then Index = 0
  403.  
  404.         End If
  405.  
  406.         Info.FileName = FileName
  407.         Info.IconIndex = Index
  408.  
  409.         Return Info
  410.     End Function
  411.  
  412. #End Region
  413.  
  414. #Region " Icon Cache "
  415.  
  416.     Function CacheBlankIcon(Extension As String) As String
  417.         If Extension = String.Empty Then Return Extension
  418.         If _ImageList.Images.ContainsKey(Extension) Then Return Extension
  419.  
  420.         _ImageList.Images.Add(Extension, New Bitmap(16, 16))
  421.         Return Extension
  422.     End Function
  423.  
  424.     Function CacheIndexedIcon(ByVal Info As EmbeddedIconInfo, Extension As String) As String
  425.         If _ImageList.Images.ContainsKey(Extension) Then Return Extension
  426.  
  427.         Try
  428.             Dim ImageIcon As Image = ExtractIconFromFile(Info).ToBitmap
  429.             _ImageList.Images.Add(Extension, ImageIcon)
  430.         Catch ex As Exception
  431.             CacheBlankIcon(Extension)
  432.         End Try
  433.         Return Extension
  434.     End Function
  435.  
  436.     Function CacheIcon(ByVal Info As EmbeddedIconInfo, Optional Extension As String = "") As String
  437.         Return CacheIcon(Info.FileName, Extension)
  438.     End Function
  439.  
  440.     Private Delegate Function IconCacheDelegate(Path As String, Extension As String) As String
  441.  
  442.     Function CacheIcon(ByVal Path As String, Optional Extension As String = "") As String
  443.         If InvokeRequired Then Invoke(New IconCacheDelegate(AddressOf CacheIcon), {Path, Extension})
  444.  
  445.         Dim Ext As String = Nothing
  446.  
  447.         Try
  448.             If Extension = "" Then
  449.                 Ext = GetExtension(Path)
  450.             Else
  451.                 Ext = Extension
  452.                 If Ext = ".exe" Or Ext = ".url" Or Ext = ".lnk" Then Ext = Path
  453.             End If
  454.  
  455.             If Not _ImageList.Images.ContainsKey(Ext) Then
  456.  
  457.                 Dim ImageIcon As Image = GetIconAsImage(Path)
  458.                 If ImageIcon IsNot Nothing Then
  459.                     _ImageList.Images.Add(Ext, ImageIcon)
  460.                 Else
  461.                     Return CacheBlankIcon(Extension)
  462.                 End If
  463.  
  464.             End If
  465.  
  466.         Catch ex As Exception
  467.             Return CacheBlankIcon(Extension)
  468.         End Try
  469.  
  470.         Return Ext
  471.     End Function
  472.  
  473.     Sub CacheIcons(Paths As DirectoryInfo())
  474.         Dim PathList As New List(Of String)
  475.  
  476.         For Each Path In Paths
  477.             PathList.Add(Path.FullName)
  478.         Next
  479.  
  480.         CacheIcons(PathList.ToArray)
  481.     End Sub
  482.  
  483.     Sub CacheIcons(Paths As FileInfo())
  484.         Dim PathList As New List(Of String)
  485.  
  486.         For Each Path In Paths
  487.             PathList.Add(Path.FullName)
  488.         Next
  489.  
  490.         CacheIcons(PathList.ToArray)
  491.     End Sub
  492.  
  493.     Sub CacheIcons(Paths As String())
  494.         Dim T As New Threading.Thread(AddressOf CacheAsync)
  495.         T.IsBackground = True
  496.         T.Start(Paths)
  497.     End Sub
  498.  
  499.     Private Sub CacheAsync(Paths As String())
  500.  
  501.         For Each Path As String In Paths
  502.             CacheIcon(Path)
  503.             Application.DoEvents()
  504.  
  505.         Next
  506.  
  507.     End Sub
  508.  
  509.     Private Function GetExtension(Path As String) As String
  510.         Dim Ext As String = ""
  511.  
  512.         If Directory.Exists(Path) Then
  513.             Ext = "folder"
  514.         ElseIf File.Exists(Path) Then
  515.             Ext = IO.Path.GetExtension(Path)
  516.         End If
  517.  
  518.         If Ext = ".exe" Or Ext = ".url" Or Ext = ".lnk" Then Ext = Path
  519.  
  520.         Return Ext
  521.     End Function
  522.  
  523.     Private Sub WindowsTreeView_Disposed(sender As Object, e As EventArgs) Handles Me.Disposed
  524.  
  525.     End Sub
  526.  
  527. #End Region
  528.  
  529.     Class WindowsFolderFile
  530.  
  531.         Sub New(Path As String)
  532.             If Path = String.Empty Then Throw New Exception("")
  533.             _Path = Path
  534.  
  535.  
  536.         End Sub
  537.  
  538.         Function GetDirectories() As DirectoryInfo()
  539.             Return New DirectoryInfo(_Path).GetDirectories
  540.         End Function
  541.  
  542.         Function GetFiles() As FileInfo()
  543.             Return New DirectoryInfo(_Path).GetFiles
  544.         End Function
  545.  
  546.         Private _Path As String
  547.         ReadOnly Property Path As String
  548.             Get
  549.                 Return _Path
  550.             End Get
  551.         End Property
  552.  
  553.         Private _ImageKey As String
  554.         ReadOnly Property ImageKey() As String
  555.             Get
  556.                 Return _ImageKey
  557.             End Get
  558.         End Property
  559.  
  560.         Private _IsFolder As Boolean
  561.         ReadOnly Property IsFolder() As Boolean
  562.             Get
  563.                 Return _IsFolder
  564.             End Get
  565.         End Property
  566.  
  567.         Private _Extension As String
  568.         ReadOnly Property Extension() As String
  569.             Get
  570.                 Return _Extension
  571.             End Get
  572.         End Property
  573.  
  574.     End Class
  575.  
  576. End Class
  577.  
  578.  
  579. Public NotInheritable Class KnownFolders
  580.  
  581. #Region " Folder GUIDs "
  582.  
  583.     Private Shared FolderGUIDs As String() =
  584.    {"{008CA0B1-55B4-4C56-B8A8-4DE4B299D3BE}",
  585.     "{724EF170-A42D-4FEF-9F26-B60E846FBA4F}",
  586.     "{A3918781-E5F2-4890-B3D9-A7E54332328C}",
  587.     "{AB5FB87B-7CE2-4F83-915D-550846C9537B}",
  588.     "{9E52AB10-F80D-49DF-ACB8-4330F5687855}",
  589.     "{D0384E7D-BAC3-4797-8F14-CBA229B392B5}",
  590.     "{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}",
  591.     "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}",
  592.     "{A4115719-D62E-491D-AA7C-E74B8BE3B067}",
  593.     "{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}",
  594.     "{B94237E7-57AC-4347-9151-B08C6C32D1F7}",
  595.     "{56784854-C6CB-462B-8169-88E350ACB882}",
  596.     "{2B0F765D-C0E9-4171-908E-08A611B84FF6}",
  597.     "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}",
  598.     "{5CE4A5E9-E4EB-479D-B89F-130C02886155}",
  599.     "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}",
  600.     "{7B0DB17D-9CD2-4A93-9733-46CC89022E7C}",
  601.     "{374DE290-123F-4565-9164-39C4925E467B}",
  602.     "{1777F761-68AD-4D8A-87BD-30B759FA33DD}",
  603.     "{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}",
  604.     "{054FAE61-4DD8-4787-80B6-090220C4B700}",
  605.     "{D9DC8A3B-B784-432E-A781-5A1130A75963}",
  606.     "{BCB5256F-79F6-4CEE-B725-DC34E402FD46}",
  607.     "{352481E8-33BE-4251-BA85-6007CAEDCF9D}",
  608.     "{1B3EA5DC-B587-4786-B4EF-BD1DC332AEAE}",
  609.     "{BFB9D5E0-C6A9-404C-B2B2-AE6DB6AF4968}",
  610.     "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}",
  611.     "{A520A1A4-1780-4FF6-BD18-167343C5AF16}",
  612.     "{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}",
  613.     "{4BD8D571-6D19-48D3-BE97-422220080E43}",
  614.     "{2112AB0A-C86A-4FFE-A368-0DE96E47012E}",
  615.     "{C5ABBF53-E17F-4121-8900-86626FC2C973}",
  616.     "{2C36C0AA-5812-4B87-BFD0-4CD0DFB19B39}",
  617.     "{69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C}",
  618.     "{A990AE9F-A03B-4E80-94BC-9912D7504104}",
  619.     "{33E28130-4E1E-4676-835A-98395C3BC3BB}",
  620.     "{DE92C1C7-837F-4F69-A3BB-86E631204A23}",
  621.     "{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}",
  622.     "{5E6C858F-0E22-4760-9AFE-EA3317B67173}",
  623.     "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}",
  624.     "{905E63B6-C1BF-494E-B29C-65B732D3D21A}",
  625.     "{6D809377-6AF0-444B-8957-A3773F02200E}",
  626.     "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}",
  627.     "{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}",
  628.     "{6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D}",
  629.     "{DE974D24-D9C6-4D3E-BF91-F4455120B917}",
  630.     "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}",
  631.     "{DFDF76A2-C82A-4D63-906A-5644AC457385}",
  632.     "{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}",
  633.     "{ED4824AF-DCE4-45A8-81E2-FC7965083634}",
  634.     "{3D644C9B-1FB8-4F30-9B45-F670235F79C0}",
  635.     "{DEBF2536-E1A8-4C59-B6A2-414586476AEA}",
  636.     "{48DAF80B-E6CF-4F4E-B800-0E69D84EE384}",
  637.     "{3214FAB5-9757-4298-BB61-92A9DEAA44FF}",
  638.     "{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}",
  639.     "{E555AB60-153B-4D17-9F04-A5FE99FC15EC}",
  640.     "{0482AF6C-08F1-4C34-8C90-E17EC98B1E17}",
  641.     "{2400183A-6185-49FB-A2D8-4A392A602BA3}",
  642.     "{52A4F021-7B75-48A9-9F6B-4B87A210BC8F}",
  643.     "{AE50C081-EBD2-438A-8655-8A092E34987A}",
  644.     "{1A6FDBA2-F42D-4358-A798-B74D745926C5}",
  645.     "{8AD10C31-2ADB-4296-A8F7-E4701232C972}",
  646.     "{C870044B-F49E-4126-A9C3-B52A1FF411E8}",
  647.     "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}",
  648.     "{AAA8D5A5-F1D6-4259-BAA8-78E7EF60835E}",
  649.     "{00BCFC5A-ED94-4E48-96A1-3F6217F21990}",
  650.     "{B250C668-F57D-4EE1-A63C-290EE7D1AA1F}",
  651.     "{C4900540-2379-4C75-844B-64E6FAF8716B}",
  652.     "{15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5}",
  653.     "{859EAD94-2E85-48AD-A71A-0969CB56A6CD}",
  654.     "{4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4}",
  655.     "{7D1D3A04-DEBB-4115-95CF-2F29DA2920DA}",
  656.     "{B7BEDE81-DF94-4682-A7D8-57A52620B86F}",
  657.     "{0D4C3DB6-03A3-462F-A0E6-08924C41B5D4}",
  658.     "{7E636BFE-DFA9-4D5E-B456-D7B39851D8A9}",
  659.     "{8983036C-27C0-404B-8F08-102D10DCFD74}",
  660.     "{7B396E54-9EC5-4300-BE0A-2482EBAE1A26}",
  661.     "{A75D362E-50FC-4FB7-AC2C-A8BEAA314493}",
  662.     "{A52BBA46-E9E1-435F-B3D9-28DAA648C0F6}",
  663.     "{767E6811-49CB-4273-87C2-20F355E1085B}",
  664.     "{24D89E24-2F19-4534-9DDE-6A6671FBB8FE}",
  665.     "{339719B5-8C47-4894-94C2-D8F77ADD44A6}",
  666.     "{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}",
  667.     "{B97D20BB-F46A-4C97-BA10-5E3608430854}",
  668.     "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}",
  669.     "{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}",
  670.     "{A63293E8-664E-48DB-A079-DF759E0509F7}",
  671.     "{9E3995AB-1F9C-4F13-B827-48B24B6C7174}",
  672.     "{0762D272-C50A-4BB0-A382-697DCD729B80}",
  673.     "{5CD7AEE2-2219-4A67-B85D-6C9CE15660CB}",
  674.     "{BCBD3057-CA5C-4622-B42D-BC56DB0AE516}",
  675.     "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}",
  676.     "{491E922F-5643-4AF4-A7EB-4E7A138D8174}",
  677.     "{F38BF404-1D43-42F2-9305-67DE0B28FC23}"}
  678.  
  679. #End Region
  680.  
  681. #Region " Imports & Enums "
  682.     ''' <summary>
  683.     ''' Retrieves the full path of a known folder identified by the folder's KnownFolderID.
  684.     ''' </summary>
  685.     ''' <param name="rfid">A KnownFolderID that identifies the folder.</param>
  686.     ''' <param name="dwFlags">Flags that specify special retrieval options. This value can be
  687.     '''     0; otherwise, one or more of the KnownFolderFlag values.</param>
  688.     ''' <param name="hToken">An access token that represents a particular user. If this
  689.     '''     parameter is NULL, which is the most common usage, the function requests the known
  690.     '''     folder for the current user. Assigning a value of -1 indicates the Default User.
  691.     '''     The default user profile is duplicated when any new user account is created.
  692.     '''     Note that access to the Default User folders requires administrator privileges.
  693.     '''     </param>
  694.     ''' <param name="ppszPath">When this method returns, contains the address of a string that
  695.     '''     specifies the path of the known folder. The returned path does not include a
  696.     '''     trailing backslash.</param>
  697.     ''' <returns>Returns S_OK if successful, or an error value otherwise.</returns>
  698.     <DllImport("Shell32.dll")>
  699.     Private Shared Function SHGetKnownFolderPath(<MarshalAs(UnmanagedType.LPStruct)> rfid As Guid, dwFlags As UInteger, hToken As IntPtr, ByRef ppszPath As IntPtr) As Integer
  700.     End Function
  701.  
  702.     ''' <summary>
  703.     ''' Standard folders registered with the system. These folders are installed with Windows Vista
  704.     ''' and later operating systems, and a computer will have only folders appropriate to it
  705.     ''' installed.
  706.     ''' </summary>
  707.  
  708.     Public Enum KnownFolder
  709.         AccountPictures
  710.         AdminTools
  711.         ApplicationShortcuts
  712.         CameraRoll
  713.         CDBurning
  714.         CommonAdminTools
  715.         CommonOemLinks
  716.         CommonPrograms
  717.         CommonStartMenu
  718.         CommonStartup
  719.         CommonTemplates
  720.         Contacts
  721.         Cookies
  722.         Desktop
  723.         DeviceMetadataStore
  724.         Documents
  725.         DocumentsLibrary
  726.         Downloads
  727.         Favorites
  728.         Fonts
  729.         GameTasks
  730.         History
  731.         ImplicitAppShortcuts
  732.         InternetCache
  733.         Libraries
  734.         Links
  735.         LocalAppData
  736.         LocalAppDataLow
  737.         LocalizedResourcesDir
  738.         Music
  739.         MusicLibrary
  740.         NetHood
  741.         OriginalImages
  742.         PhotoAlbums
  743.         PicturesLibrary
  744.         Pictures
  745.         Playlists
  746.         PrintHood
  747.         Profile
  748.         ProgramData
  749.         ProgramFiles
  750.         ProgramFilesX64
  751.         ProgramFilesX86
  752.         ProgramFilesCommon
  753.         ProgramFilesCommonX64
  754.         ProgramFilesCommonX86
  755.         Programs
  756.         [Public]
  757.         PublicDesktop
  758.         PublicDocuments
  759.         PublicDownloads
  760.         PublicGameTasks
  761.         PublicLibraries
  762.         PublicMusic
  763.         PublicPictures
  764.         PublicRingtones
  765.         PublicUserTiles
  766.         PublicVideos
  767.         QuickLaunch
  768.         Recent
  769.         RecordedTVLibrary
  770.         ResourceDir
  771.         Ringtones
  772.         RoamingAppData
  773.         RoamedTileImages
  774.         RoamingTiles
  775.         SampleMusic
  776.         SamplePictures
  777.         SamplePlaylists
  778.         SampleVideos
  779.         SavedGames
  780.         SavedSearches
  781.         Screenshots
  782.         SearchHistory
  783.         SearchTemplates
  784.         SendTo
  785.         SidebarDefaultParts
  786.         SidebarParts
  787.         SkyDrive
  788.         SkyDriveCameraRoll
  789.         SkyDriveDocuments
  790.         SkyDrivePictures
  791.         StartMenu
  792.         Startup
  793.         System
  794.         SystemX86
  795.         Templates
  796.         UserPinned
  797.         UserProfiles
  798.         UserProgramFiles
  799.         UserProgramFilesCommon
  800.         Videos
  801.         VideosLibrary
  802.         Windows
  803.     End Enum
  804.  
  805.     <Flags>
  806.     Private Enum KnownFolderFlags As UInteger
  807.         SimpleIDList = &H100
  808.         NotParentRelative = &H200
  809.         DefaultPath = &H400
  810.         Init = &H800
  811.         NoAlias = &H1000
  812.         DontUnexpand = &H2000
  813.         DontVerify = &H4000
  814.         Create = &H8000
  815.         NoAppcontainerRedirection = &H10000
  816.         AliasOnly = &H80000000UI
  817.     End Enum
  818.  
  819. #End Region
  820.  
  821. #Region " Sub Routines "
  822.  
  823.     ''' <summary>
  824.     ''' Gets the current path to the specified known folder as currently configured. This does
  825.     ''' not require the folder to be existent.
  826.     ''' </summary>
  827.     ''' <param name="knownFolder">The known folder which current path will be returned.</param>
  828.     ''' <returns>The default path of the known folder.</returns>
  829.     ''' <exception cref="System.Runtime.InteropServices.ExternalException">Thrown if the path
  830.     '''     could not be retrieved.</exception>
  831.     Public Shared Function GetPath(knownFolder As KnownFolder) As String
  832.         Return GetPath(knownFolder, False)
  833.     End Function
  834.  
  835.     ''' <summary>
  836.     ''' Gets the current path to the specified known folder as currently configured. This does
  837.     ''' not require the folder to be existent.
  838.     ''' </summary>
  839.     ''' <param name="knownFolder">The known folder which current path will be returned.</param>
  840.     ''' <param name="defaultUser">Specifies if the paths of the default user (user profile
  841.     '''     template) will be used. This requires administrative rights.</param>
  842.     ''' <returns>The default path of the known folder.</returns>
  843.     ''' <exception cref="ExternalException">Thrown if the path
  844.     '''     could not be retrieved.</exception>
  845.     Public Shared Function GetPath(knownFolder As KnownFolder, defaultUser As Boolean) As String
  846.         Return GetPath(knownFolder, KnownFolderFlags.DontVerify, defaultUser)
  847.     End Function
  848.  
  849.     ''' <summary>
  850.     ''' Gets the default path to the specified known folder. This does not require the folder
  851.     ''' to be existent.
  852.     ''' </summary>
  853.     ''' <param name="knownFolder">The known folder which default path will be returned.</param>
  854.     ''' <returns>The current (and possibly redirected) path of the known folder.</returns>
  855.     ''' <exception cref="ExternalException">Thrown if the path
  856.     '''     could not be retrieved.</exception>
  857.     Public Shared Function GetDefaultPath(knownFolder As KnownFolder) As String
  858.         Return GetDefaultPath(knownFolder, False)
  859.     End Function
  860.  
  861.     ''' <summary>
  862.     ''' Gets the default path to the specified known folder. This does not require the folder
  863.     ''' to be existent.
  864.     ''' </summary>
  865.     ''' <param name="knownFolder">The known folder which default path will be returned.</param>
  866.     ''' <param name="defaultUser">Specifies if the paths of the default user (user profile
  867.     '''     template) will be used. This requires administrative rights.</param>
  868.     ''' <returns>The current (and possibly redirected) path of the known folder.</returns>
  869.     ''' <exception cref="ExternalException">Thrown if the path
  870.     '''     could not be retrieved.</exception>
  871.     Public Shared Function GetDefaultPath(knownFolder As KnownFolder, defaultUser As Boolean) As String
  872.         Return GetPath(knownFolder, KnownFolderFlags.DefaultPath Or KnownFolderFlags.DontVerify, defaultUser)
  873.     End Function
  874.  
  875.     ''' <summary>
  876.     ''' Creates and initializes the known folder.
  877.     ''' </summary>
  878.     ''' <param name="knownFolder">The known folder which will be initialized.</param>
  879.     ''' <exception cref="ExternalException">Thrown if the known
  880.     '''     folder could not be initialized.</exception>
  881.     Public Shared Sub Initialize(knownFolder As KnownFolder)
  882.         Initialize(knownFolder, False)
  883.     End Sub
  884.  
  885.     ''' <summary>
  886.     ''' Creates and initializes the known folder.
  887.     ''' </summary>
  888.     ''' <param name="knownFolder">The known folder which will be initialized.</param>
  889.     ''' <param name="defaultUser">Specifies if the paths of the default user (user profile
  890.     '''     template) will be used. This requires administrative rights.</param>
  891.     ''' <exception cref="ExternalException">Thrown if the known
  892.     '''     folder could not be initialized.</exception>
  893.     Public Shared Sub Initialize(knownFolder As KnownFolder, defaultUser As Boolean)
  894.         GetPath(knownFolder, KnownFolderFlags.Create Or KnownFolderFlags.Init, defaultUser)
  895.     End Sub
  896.  
  897.     Private Shared Function GetPath(knownFolder As KnownFolder, flags As KnownFolderFlags, defaultUser As Boolean) As String
  898.         Dim outPath As IntPtr
  899.         Dim result As Integer = SHGetKnownFolderPath(New Guid(FolderGUIDs(CInt(knownFolder))), CUInt(flags), New IntPtr(If(defaultUser, -1, 0)), outPath)
  900.         If result >= 0 Then
  901.             Return Marshal.PtrToStringUni(outPath)
  902.         Else
  903.             Throw New ExternalException("Unable to retrieve the known folder path. It may not " + "be available on this system.", result)
  904.         End If
  905.         Marshal.FreeCoTaskMem(outPath)
  906.     End Function
  907.  
  908. #End Region
  909.  
  910. End Class
Advertisement
Add Comment
Please, Sign In to add comment