【转】 C# ListView实例:文件图标显示

【转】 C# ListView实例:文件图标显示

说明:本例将目录中的文件显示在窗体的ListView控件中,并定义了多种视图浏览。通过调用Win32库函数实现图标数据的提取。

主程序:

大图标:

列表:

详细信息:

Form1.cs:

public partial class Form1 : Form
    {
        FileInfoList fileList;

        public Form1()
        {
            InitializeComponent();
        }

        private void 加载文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string[] filespath = Directory.GetFiles(dlg.SelectedPath);
                fileList = new FileInfoList(filespath);
                InitListView();
            }
        }

        private void InitListView()
        {
            listView1.Items.Clear();
            this.listView1.BeginUpdate();
            foreach (FileInfoWithIcon file in fileList.list)
            {
                ListViewItem item = new ListViewItem();
                item.Text = file.fileInfo.Name.Split(‘.‘)[0];
                item.ImageIndex = file.iconIndex;
                item.SubItems.Add(file.fileInfo.LastWriteTime.ToString());
                item.SubItems.Add(file.fileInfo.Extension.Replace(".",""));
                item.SubItems.Add(string.Format(("{0:N0}"), file.fileInfo.Length));
                listView1.Items.Add(item);
            }
            listView1.LargeImageList = fileList.imageListLargeIcon;
            listView1.SmallImageList = fileList.imageListSmallIcon;
            listView1.Show();
            this.listView1.EndUpdate();
        }

        private void 大图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.LargeIcon;
        }

        private void 小图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.SmallIcon;
        }

        private void 平铺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.Tile;
        }

        private void 列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.List;
        }

        private void 详细信息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listView1.View = View.Details;
        }
    }

FileInfoList.cs:

说明:主要用于后台数据的存储

class FileInfoList
    {
        public List<FileInfoWithIcon> list;
        public ImageList imageListLargeIcon;
        public ImageList imageListSmallIcon;

        /// <summary>
        /// 根据文件路径获取生成文件信息,并提取文件的图标
        /// </summary>
        /// <param name="filespath"></param>
        public FileInfoList(string[] filespath)
        {
            list = new List<FileInfoWithIcon>();
            imageListLargeIcon = new ImageList();
            imageListLargeIcon.ImageSize = new Size(32, 32);
            imageListSmallIcon = new ImageList();
            imageListSmallIcon.ImageSize = new Size(16, 16);
            foreach (string path in filespath)
            {
                FileInfoWithIcon file = new FileInfoWithIcon(path);
                imageListLargeIcon.Images.Add(file.largeIcon);
                imageListSmallIcon.Images.Add(file.smallIcon);
                file.iconIndex = imageListLargeIcon.Images.Count - 1;
                list.Add(file);
            }
        }
    }
    class FileInfoWithIcon
    {
        public FileInfo fileInfo;
        public Icon largeIcon;
        public Icon smallIcon;
        public int iconIndex;
        public FileInfoWithIcon(string path)
        {
            fileInfo = new FileInfo(path);
            largeIcon = GetSystemIcon.GetIconByFileName(path, true);
            if (largeIcon == null)
                largeIcon = GetSystemIcon.GetIconByFileType(Path.GetExtension(path), true);

            smallIcon = GetSystemIcon.GetIconByFileName(path, false);
            if (smallIcon == null)
                smallIcon = GetSystemIcon.GetIconByFileType(Path.GetExtension(path), false);
        }
    }

GetSystemIcon:

说明:定义两种图标获取方式,从文件提取和从文件关联的系统资源中提取。

public static class GetSystemIcon
    {
        /// <summary>
        /// 依据文件名读取图标,若指定文件不存在,则返回空值。
        /// </summary>
        /// <param name="fileName">文件路径</param>
        /// <param name="isLarge">是否返回大图标</param>
        /// <returns></returns>
        public static Icon GetIconByFileName(string fileName, bool isLarge = true)
        {
            int[] phiconLarge = new int[1];
            int[] phiconSmall = new int[1];
            //文件名 图标索引
            Win32.ExtractIconEx(fileName, 0, phiconLarge, phiconSmall, 1);
            IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);

            if (IconHnd.ToString() == "0")
                return null;
            return Icon.FromHandle(IconHnd);
        }

        /// <summary>
        /// 根据文件扩展名(如:.*),返回与之关联的图标。
        /// 若不以"."开头则返回文件夹的图标。
        /// </summary>
        /// <param name="fileType">文件扩展名</param>
        /// <param name="isLarge">是否返回大图标</param>
        /// <returns></returns>
        public static Icon GetIconByFileType(string fileType, bool isLarge)
        {
            if (fileType == null || fileType.Equals(string.Empty)) return null;

            RegistryKey regVersion = null;
            string regFileType = null;
            string regIconString = null;
            string systemDirectory = Environment.SystemDirectory + "\\";

            if (fileType[0] == ‘.‘)
            {
                //读系统注册表中文件类型信息
                regVersion = Registry.ClassesRoot.OpenSubKey(fileType, false);
                if (regVersion != null)
                {
                    regFileType = regVersion.GetValue("") as string;
                    regVersion.Close();
                    regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon", false);
                    if (regVersion != null)
                    {
                        regIconString = regVersion.GetValue("") as string;
                        regVersion.Close();
                    }
                }
                if (regIconString == null)
                {
                    //没有读取到文件类型注册信息,指定为未知文件类型的图标
                    regIconString = systemDirectory + "shell32.dll,0";
                }
            }
            else
            {
                //直接指定为文件夹图标
                regIconString = systemDirectory + "shell32.dll,3";
            }
            string[] fileIcon = regIconString.Split(new char[] { ‘,‘ });
            if (fileIcon.Length != 2)
            {
                //系统注册表中注册的标图不能直接提取,则返回可执行文件的通用图标
                fileIcon = new string[] { systemDirectory + "shell32.dll", "2" };
            }
            Icon resultIcon = null;
            try
            {
                //调用API方法读取图标
                int[] phiconLarge = new int[1];
                int[] phiconSmall = new int[1];
                uint count = Win32.ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1);
                IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
                resultIcon = Icon.FromHandle(IconHnd);
            }
            catch { }
            return resultIcon;
        }
    }

    /// <summary>
    /// 定义调用的API方法
    /// </summary>
    class Win32
    {
        [DllImport("shell32.dll")]
        public static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);
    }

时间: 2024-08-02 23:27:39

【转】 C# ListView实例:文件图标显示的相关文章

TortoiseGit 文件图标显示灰色对号

通过查看TortoiseGit属性,我们得知,灰色对号代表的是assume-valid,也就是git中assume-unchanged的意思,通过如下步骤,可以去掉该灰色对号: 对于untrack的文件,我们可以创建.gitignore文件. 对于已经track的文件,我们可以这样做: git update-index –assume-unchanged 这样,即使已经更改了文件,用git status也不会看见文件已经更改(assume-valid). 但在使用时需要小心,取消这种设定可以使用

Eclipse或MyEclipse没有在java类文件上显示Spring图标的问题

Eclipse或MyEclipse没有在java类文件上显示接口图标的问题解决办法: 前: 后:

Android Studio 那些事|Activity文件前标识图标显示为 j 而是 c

问题:Activity文件前标识图标显示为 j 而是 c 的图标,或是没有显示,而且自动提示不提示 解决:这是因为你的studio设置了省电模式,你可以通过 File>Power Save Mode取消掉,或者通过点击右下角小人头像取消 版权声明:本文为博主原创文章,未经博主允许不得转载.

Ubuntu上安装火狐浏览器无法固定到启动器上,火狐图标显示异常 文件夹右键重命名选项变灰时重命名方法

http://blog.csdn.net/pipisorry/article/details/39483361 Ubuntu自带火狐浏览器,可是使用起来不好,并且版本还可能过旧,因此将其卸载(不卸载的话总是指向旧版本的firefox),于是从火狐官网上下载firefox并解压到/opt文件夹下. 不过下载的火狐无法固定到启动器上(可能看到固定上了,但是无法运行),并且图标似乎分辨率比较低,看起来比较模糊.),删除了:/home/qiyo/.mozilla/目录,然后才能固定上. 找到/opt文件

svn安装后文件不显示图标

我将svn安装完成,从svn上下载文件后,可以提交和更新,但是显示不出,文件是否和svn保持一致的图标.先看一下完成后的文件夹样子. 完成步骤如下: 1.在文件的任意位置右键,选择TortoiseSVN---settings ----icon overlays 选择 shell 点击"确定" 2.将svn的安装文件双击点击Repair后,等待svn修复完成后,刷新文件夹即可. svn安装后文件不显示图标

Git文件不显示图标/标识

初次使用Git服务功能,做了很多探路事情,记录下刚刚遇到的问题 情况:安装了Git应用程序,或者也安装了TortoiseGit-1.8.16.0-64bit(类似SVN工具)后,上传下载文件没有问题,只是文件上没有相对应标识 类似这种: 3.解决方案 第一种方案: win+r,regedit.exe,打开注册表 按照文件的层次关系依次找到 HKEY_LOCAL_MACHINE\Software\Microsoft\windows\CurrentVersion\Explorer; 修改键名 Max

C#类似windows资源管理器-获取文件图标

在做文件管理器的过程中,有一个非常重要的功能实现,就是对不同的文件类型获取文件的描述信息,以及对文件图标的获取 实现这个功能需要调用Windows API,以及对注册表的操作(代码是看了一些网上写的后根据自己的理解写了一个比较简洁易懂的代码) 下面看代码: //根据扩展名获取图标 public int fileExtIcon(string typeExt, FileInfo f) { if (!extIcon.ContainsKey(typeExt) && typeExt != "

C# 获取文件图标

今天突然想到一个问题,如何去获取一个文件的关联图标呢?于是就上网搜索了一下.现总结如下: 首先明确问题:获取一个文件的关联图标或者是某个类型文件的显示图标. 在网上搜了一圈,发现方法还是比较多的,但是应用C#进行获取的方法不多.我选择一种用.Net库的方法. 使用的类: System.Drawing.Icon ,位于System.Drawing 命名空间. 具体方法: System.Drawing.Icon 类中的静态方法:public static Icon ExtractAssociated

C# 自定义文件图标 双击启动 (修改注册表)

程序生成的自定义文件,比如后缀是.test 这种文件怎么直接启动打开程序,并打开本文件呢 1.双击打开 2.自定义的文件,有图标显示 3.自定义的文件,点击右键有相应的属性 后台代码:(如何在注册表中修改信息) //工具启动路径 string toolPath = System.Windows.Forms.Application.StartupPath + "\\邮件小工具.exe"; string extension = SptdConst.FileExtension; string