热门标签 | HotTags
当前位置:  开发笔记 > 开发工具 > 正文

c#用Treeview实现FolderBrowerDialog和动态获取系统图标(运用了Win32dll类库)

其实,FolderBrowerDialog很好用呢,有木有啊亲。反正我特别的喜欢,微软大哥把这个浏览文件夹的东东封装的多好呀,可是遇到一个变态的客户就不好玩了。

事情是这样子的。我需要做一个下面的东东:

这个不难啊,然后就用FolderBrowerDialog这个神器,嗯 还不错,刚开始客户用了也很喜欢。

可是过了一段时间之后,客户说 要屏蔽右键功能,他不想让其他通过右键能打开或浏览文件夹,如下面 红色要给屏蔽。

我一开始以为只是一个参数问题,就爽快的答应了客户咯。可是啊后来找啊找 找到天荒地老也木有找到。。。放弃了,然后改用了TreeView。。结果,版本出来了,先截图:

好吧,确实很丑哦。。

代码如下:

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;
              }
          }
      }

虽然 这个时候,把右键点击功能给取消啦,但是接着用户提了三个要求:

1.需要系统自动匹配它的图标

2.要有磁盘容量的大小。。

好吧,然后最后修改一下。这里面用到了 Win32 dll的几个函数,确实很好用呢。。赞一个。。

代码如下:

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;
            [MarshalAs(UnmanagedType.ByValTStr, SizeCOnst= 260)]
            public string szDisplayName;
            [MarshalAs(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;
        }
    }
}

结果如下:

核心代码是:

代码如下:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SHFILEINFO
        {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeCOnst= 260)]
            public string szDisplayName;
            [MarshalAs(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;
        }

很好懂呢,只需要在程序中调用一下就ok啦。

作者:Lanny☆兰东才
出处:http://www.cnblogs.com/damonlan
Q Q:*********
E_mail:Damon_lan@163.com or Dongcai.lan@hp.com

本博文欢迎大家浏览和转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,在『参考』的文章中,我会表明参考的文章来源,尊重他人版权。若您发现我侵犯了您的版权,请及时与我联系。


推荐阅读
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • 本文详细介绍了GetModuleFileName函数的用法,该函数可以用于获取当前模块所在的路径,方便进行文件操作和读取配置信息。文章通过示例代码和详细的解释,帮助读者理解和使用该函数。同时,还提供了相关的API函数声明和说明。 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • windows便签快捷键_用了windows十几年,没想到竟然这么好用!隐藏的功能你知道吗?
    本文介绍了使用windows操作系统时的一些隐藏功能,包括便签快捷键、截图功能等。同时探讨了windows和macOS操作系统之间的优劣比较,以及人们对于这两个系统的不同看法。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 本文是一位90后程序员分享的职业发展经验,从年薪3w到30w的薪资增长过程。文章回顾了自己的青春时光,包括与朋友一起玩DOTA的回忆,并附上了一段纪念DOTA青春的视频链接。作者还提到了一些与程序员相关的名词和团队,如Pis、蛛丝马迹、B神、LGD、EHOME等。通过分享自己的经验,作者希望能够给其他程序员提供一些职业发展的思路和启示。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了在Windows 8上安装gvim中插件时出现的错误加载问题。作者将EasyMotion插件放在了正确的位置,但加载时却出现了错误。作者提供了下载链接和之前放置插件的位置,并列出了出现的错误信息。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文介绍了C#中生成随机数的三种方法,并分析了其中存在的问题。首先介绍了使用Random类生成随机数的默认方法,但在高并发情况下可能会出现重复的情况。接着通过循环生成了一系列随机数,进一步突显了这个问题。文章指出,随机数生成在任何编程语言中都是必备的功能,但Random类生成的随机数并不可靠。最后,提出了需要寻找其他可靠的随机数生成方法的建议。 ... [详细]
  • 本文介绍了在Hibernate配置lazy=false时无法加载数据的问题,通过采用OpenSessionInView模式和修改数据库服务器版本解决了该问题。详细描述了问题的出现和解决过程,包括运行环境和数据库的配置信息。 ... [详细]
  • Win10下游戏不能全屏的解决方法及兼容游戏列表
    本文介绍了Win10下游戏不能全屏的解决方法,包括修改注册表默认值和查看兼容游戏列表。同时提供了部分已经支持Win10的热门游戏列表,帮助玩家解决游戏不能全屏的问题。 ... [详细]
  • 如何在联想win10专业版中修改账户名称
    本文介绍了在联想win10专业版中修改账户名称的方法,包括在计算机管理中找到要修改的账户,通过重命名来修改登录名和属性来修改显示名称。同时指出了windows10家庭版无法使用此方法的限制。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • Windows下配置PHP5.6的方法及注意事项
    本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
author-avatar
晓雷sky
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有