C # Use Treeview to implement FolderBrowerDialog and Dynamically Retrieve system icons (using the Win32 dll Class Library)

Source: Internet
Author: User

This is the case. I need to do the following:

This is not difficult. Then we use the FolderBrowerDialog. Well, it's good. At first, the customer liked it.

After a while, the customer said that the right-click feature should be blocked, and he did not want others to open or browse folders by right-clicking, as shown in red below.

At first I thought it was just a parameter problem, so I readily agreed to the customer. However, you can find it later... Give up, and then use TreeView .. As a result, the version is released. First:

Well, it's really ugly ..

Copy codeThe Code is as follows: public MyDirectory ()
{
InitializeComponent ();
TreeViewDirectory. BeginUpdate ();
Label1.Text = folderTitle;
TreeViewDirectory. ImageList = imageList1;
TreeViewDirectory. SelectedImageIndex = 3;
EnumDrivers ();
TreeViewDirectory. EndUpdate ();

This. setBounds (Screen. getBounds (this ). width/2)-(this. width/2), (Screen. getBounds (this ). height/2)-(this. height/2), this. width, this. height, BoundsSpecified. location );
}
Public static string folderTitle = "";
Private void EnumDrivers ()
{
// TreeViewDirectory. ImageIndex = 1;
String [] allDriveNames = Directory. GetLogicalDrives ();
TreeNode rootNode = new TreeNode ();
RootNode. Text = "My Computer ";
RootNode. ImageIndex = 1;
RootNode. Expand ();
TreeViewDirectory. Nodes. Add (rootNode );
TreeViewDirectory. SelectedNode = rootNode. FirstNode;
DriveInfo [] allDrives = DriveInfo. GetDrives ();
Int j = 0;
Try
{
Int I = 0;
Foreach (DriveInfo d in allDrives)
{
TreeNode tn = new TreeNode (d. Name );

// GetIcon (d. Name, false)
This. imageList1.Images. Add (GetIcon (d. Name, false ));

Tn. ImageIndex = 2;

Tn. Tag = d. RootDirectory. FullName;
TreeViewDirectory. Nodes [0]. Nodes. Add (tn );
TreeViewDirectory. Nodes [0]. Nodes [j]. Text = d. Name;
ShowDirs (tn );
J ++;
}
}
Catch (System. Exception)
{
}
}

Private void ShowDirs (TreeNode tn)
{
Tn. Nodes. Clear ();
Try
{
DirectoryInfo DirInfo = new DirectoryInfo (tn. Tag. ToString ());
If (! DirInfo. Exists)
{
Return;
}
Else
{
DirectoryInfo [] Dirs;
Try
{
Dirs = DirInfo. GetDirectories ();
}
Catch (Exception e)
{
Return;
}
Foreach (DirectoryInfo Dir in Dirs)
{
TreeNode dir = new TreeNode (Dir. Name );
Dir. ImageIndex = 0;
Dir. Tag = Dir. FullName;
Tn. Nodes. Add (dir );
}
}
}
Catch (System. Exception)
{}
}

Private void treeViewDirectory_BeforeExpand (object sender, TreeViewCancelEventArgs e)
{
TreeViewDirectory. BeginUpdate ();
Foreach (TreeNode tn in e. Node. Nodes)
{
ShowDirs (tn );
}
TreeViewDirectory. EndUpdate ();
}

Public static string myValue {set; get ;}
Private void btnOK_Click (object sender, EventArgs e)
{
MyDirectory. myValue = lastResult;
This. Close ();
}

Private void btnCancel_Click (object sender, EventArgs e)
{
MyDirectory. myValue = null;
This. Close ();
}
Private static string lastResult = null;
Private void treeViewDirectory_NodeMouseClick (object sender, TreeNodeMouseClickEventArgs e)
{
LastResult = null;
String result = e. Node. FullPath;
If (result! = "My Computer ")
{
If (result. Contains (@ "My Computer \") | result. Contains ("My Computer "))
{
Int len = 0;
If (result. Contains (@ "My Computer \"))
{
Len = @ "My Computer \". Length;
}
Else
{
Len = "My Computer". Length;
}
Result = result. Substring (len );
Return result;
}
}
}

At this time, the right-click function is canceled, but the user has three requirements:

1. The system needs to automatically match its icon

2. the disk capacity is required ..

Okay, then modify it. Several Functions of Win32 dll are used here, which is really useful .. Like one ..

Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Text;
Using System. Windows. Forms;
Using System. IO;
Using System. Runtime. InteropServices;

Namespace HP. DMT. UI
{
Public partial class MyDirectory: Form
{

Public MyDirectory ()
{
InitializeComponent ();
TreeViewDirectory. BeginUpdate ();
Label1.Text = folderTitle;
TreeViewDirectory. ImageList = imageList1;
TreeViewDirectory. SelectedImageIndex = 3;
EnumDrivers ();
TreeViewDirectory. EndUpdate ();

This. setBounds (Screen. getBounds (this ). width/2)-(this. width/2), (Screen. getBounds (this ). height/2)-(this. height/2), this. width, this. height, BoundsSpecified. location );
}
Public static string folderTitle = "";
Private void EnumDrivers ()
{
// TreeViewDirectory. ImageIndex = 1;
String [] allDriveNames = Directory. GetLogicalDrives ();
TreeNode rootNode = new TreeNode ();
RootNode. Text = "My Computer ";
RootNode. ImageIndex = 1;
RootNode. Expand ();
TreeViewDirectory. Nodes. Add (rootNode );
TreeViewDirectory. SelectedNode = rootNode. FirstNode;
DriveInfo [] allDrives = DriveInfo. GetDrives ();
Int j = 0;
Try
{
Int I = 0;
Foreach (DriveInfo d in allDrives)
{
TreeNode tn = new TreeNode (d. Name );

// GetIcon (d. Name, false)
This. imageList1.Images. Add (GetIcon (d. Name, false ));

Tn. ImageIndex = 4 + I;
I ++;
Tn. Tag = d. RootDirectory. FullName;
TreeViewDirectory. Nodes [0]. Nodes. Add (tn );
If (d. DriveType. ToString () = "Fixed ")
{
TreeViewDirectory. nodes [0]. nodes [j]. text = d. name + "(" + d. driveType. toString () + "," + d. totalFreeSpace/1024/1024/1024 + "G/" + d. totalSize/1024/1024/1024 + "G )";
}
Else
{
TreeViewDirectory. Nodes [0]. Nodes [j]. Text = d. Name + "(" + d. DriveType. ToString () + ")";
}
ShowDirs (tn );
J ++;
}
}
Catch (System. Exception)
{
}
}

Private void ShowDirs (TreeNode tn)
{
Tn. Nodes. Clear ();
Try
{
DirectoryInfo DirInfo = new DirectoryInfo (tn. Tag. ToString ());
If (! DirInfo. Exists)
{
Return;
}
Else
{
DirectoryInfo [] Dirs;
Try
{
Dirs = DirInfo. GetDirectories ();
}
Catch (Exception e)
{
Return;
}
Foreach (DirectoryInfo Dir in Dirs)
{
TreeNode dir = new TreeNode (Dir. Name );
Dir. ImageIndex = 0;
Dir. Tag = Dir. FullName;
Tn. Nodes. Add (dir );
}
}
}
Catch (System. Exception)
{}
}

Private void treeViewDirectory_BeforeExpand (object sender, TreeViewCancelEventArgs e)
{
TreeViewDirectory. BeginUpdate ();
Foreach (TreeNode tn in e. Node. Nodes)
{
ShowDirs (tn );
}
TreeViewDirectory. EndUpdate ();
}

Public static string myValue {set; get ;}
Private void btnOK_Click (object sender, EventArgs e)
{
MyDirectory. myValue = lastResult;
This. Close ();
}

Private void btnCancel_Click (object sender, EventArgs e)
{
MyDirectory. myValue = null;
This. Close ();
}
Private static string lastResult = null;
Private void treeViewDirectory_NodeMouseClick (object sender, TreeNodeMouseClickEventArgs e)
{
LastResult = null;
String result = e. Node. FullPath;
If (result! = "My Computer ")
{
If (result. Contains (@ "My Computer \") | result. Contains ("My Computer "))
{
Int len = 0;
If (result. Contains (@ "My Computer \"))
{
Len = @ "My Computer \". Length;
}
Else
{
Len = "My Computer". Length;
}
Result = result. Substring (len );

Char [] arrs = result. ToCharArray ();
Int beforLenth = result. Remove (result. IndexOf ('/') + 1). Length;
Int afterLenth = result. substring (result. indexOf ('/') + 1 ). remove (result. substring (result. indexOf ('/') + 1 ). indexOf (')')). length;

Char [] c = {')'};
String str1 = result. Substring (0, 3 );
String str2 = result. Substring (result. IndexOfAny (c, beforLenth + afterLenth, 1) + 1 );

LastResult = str1 + str2;
}
}
}

[StructLayout (LayoutKind. Sequential, CharSet = CharSet. Auto)]
Public struct SHFILEINFO
{
Public IntPtr hIcon;
Public int iIcon;
Public uint dwAttributes;
[Financialas (UnmanagedType. ByValTStr, SizeConst = 260)]
Public string szDisplayName;
[Financialas (UnmanagedType. ByValTStr, SizeConst = 80)]
Public string szTypeName;
}

[DllImport ("Shell32.dll", EntryPoint = "SHGetFileInfo", SetLastError = true, CharSet = CharSet. Auto)]
Public static extern IntPtr SHGetFileInfo (string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags );

[DllImport ("User32.dll", EntryPoint = "DestroyIcon")]
Public static extern int DestroyIcon (IntPtr hIcon );

Public const uint SHGFI_ICON = 0x100;
Public const uint SHGFI_LARGEICON = 0x0;
Public const uint SHGFI_SMALLICON = 0x1;
Public const uint SHGFI_USEFILEATTRIBUTES = 0x10;

Static Icon GetIcon (string fileName, bool isLargeIcon)
{
SHFILEINFO shfi = new SHFILEINFO ();
IntPtr hI;

If (isLargeIcon)
HI = MyDirectory. SHGetFileInfo (fileName, 0, ref shfi,
(Uint) Marshal. SizeOf (shfi), MyDirectory. SHGFI_ICON | MyDirectory. SHGFI_USEFILEATTRIBUTES | MyDirectory. SHGFI_LARGEICON );
Else
HI = MyDirectory. SHGetFileInfo (fileName, 0, ref shfi, (uint) Marshal. SizeOf (shfi), MyDirectory. SHGFI_ICON | MyDirectory. SHGFI_USEFILEATTRIBUTES | MyDirectory. SHGFI_SMALLICON );
Icon icon = Icon. FromHandle (shfi. hIcon). Clone () as Icon;
MyDirectory. DestroyIcon (shfi. hIcon );
Return icon;
}
}
}

The result is as follows:

The core code is:

Copy codeThe Code is as follows: [StructLayout (LayoutKind. Sequential, CharSet = CharSet. Auto)]
Public struct SHFILEINFO
{
Public IntPtr hIcon;
Public int iIcon;
Public uint dwAttributes;
[Financialas (UnmanagedType. ByValTStr, SizeConst = 260)]
Public string szDisplayName;
[Financialas (UnmanagedType. ByValTStr, SizeConst = 80)]
Public string szTypeName;
}

[DllImport ("Shell32.dll", EntryPoint = "SHGetFileInfo", SetLastError = true, CharSet = CharSet. Auto)]
Public static extern IntPtr SHGetFileInfo (string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags );

[DllImport ("User32.dll", EntryPoint = "DestroyIcon")]
Public static extern int DestroyIcon (IntPtr hIcon );

Public const uint SHGFI_ICON = 0x100;
Public const uint SHGFI_LARGEICON = 0x0;
Public const uint SHGFI_SMALLICON = 0x1;
Public const uint SHGFI_USEFILEATTRIBUTES = 0x10;

Static Icon GetIcon (string fileName, bool isLargeIcon)
{
SHFILEINFO shfi = new SHFILEINFO ();
IntPtr hI;

If (isLargeIcon)
HI = MyDirectory. SHGetFileInfo (fileName, 0, ref shfi,
(Uint) Marshal. SizeOf (shfi), MyDirectory. SHGFI_ICON | MyDirectory. SHGFI_USEFILEATTRIBUTES | MyDirectory. SHGFI_LARGEICON );
Else
HI = MyDirectory. SHGetFileInfo (fileName, 0, ref shfi, (uint) Marshal. SizeOf (shfi), MyDirectory. SHGFI_ICON | MyDirectory. SHGFI_USEFILEATTRIBUTES | MyDirectory. SHGFI_SMALLICON );
Icon icon = Icon. FromHandle (shfi. hIcon). Clone () as Icon;
MyDirectory. DestroyIcon (shfi. hIcon );
Return icon;
}

It's easy to understand. You just need to call it in the program.

Author: Lanny ☆landong Cai
Source: http://www.cnblogs.com/damonlan
Q :*********
E_mail: Damon_lan@163.com or Dongcai.lan@hp.com

You are welcome to browse and repost this blog post, but this statement must be retained without the author's consent, and the original article connection is clearly provided on the article page. In the reference article, I will indicate the source of the reference article and respect the copyright of others. If you find that I infringe your copyright, please contact me in time.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.