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

c#根据文件类型获取相关类型图标的方法代码

c#根据文件类型获取相关类型图标的方法代码,需要的朋友可以参考一下

代码如下:

using System;
using System.Collections.Generic;
using System.Text;

namespace WindowsFormsApplication1
{
    using System;
    using System.Drawing;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;
    using System.Reflection;
    using System.Collections.Generic;

    namespace BlackFox.Win32
    {
        public static class Icons
        {
            #region Custom exceptions class

            public class IconNotFoundException : Exception
            {
                public IconNotFoundException(string fileName, int index)
                    : base(string.Format("Icon with Id = {0} wasn't found in file {1}", index, fileName))
                {
                }
            }

            public class UnableToExtractIconsException : Exception
            {
                public UnableToExtractIconsException(string fileName, int firstIconIndex, int iconCount)
                    : base(string.Format("Tryed to extract {2} icons starting from the one with id {1} from the \"{0}\" file but failed", fileName, firstIconIndex, iconCount))
                {
                }
            }

            #endregion

            #region DllImports

            ///
            /// Contains information about a file object.
            ///

            struct SHFILEINFO
            {
                ///
                /// Handle to the icon that represents the file. You are responsible for
                /// destroying this handle with DestroyIcon when you no longer need it.
                ///

                public IntPtr hIcon;

                ///
                /// Index of the icon image within the system image list.
                ///

                public IntPtr iIcon;

                ///
                /// Array of values that indicates the attributes of the file object.
                /// For information about these values, see the IShellFolder::GetAttributesOf
                /// method.
                ///

                public uint dwAttributes;

                ///
                /// String that contains the name of the file as it appears in the Microsoft
                /// Windows Shell, or the path and file name of the file that contains the
                /// icon representing the file.
                ///

                [MarshalAs(UnmanagedType.ByValTStr, SizeCOnst= 260)]
                public string szDisplayName;

                ///
                /// String that describes the type of file.
                ///

                [MarshalAs(UnmanagedType.ByValTStr, SizeCOnst= 80)]
                public string szTypeName;
            };

            [Flags]
            enum FileInfoFlags : int
            {
                ///
                /// Retrieve the handle to the icon that represents the file and the index
                /// of the icon within the system image list. The handle is copied to the
                /// hIcon member of the structure specified by psfi, and the index is copied
                /// to the iIcon member.
                ///

                SHGFI_ICON = 0x000000100,
                ///
                /// Indicates that the function should not attempt to access the file
                /// specified by pszPath. Rather, it should act as if the file specified by
                /// pszPath exists with the file attributes passed in dwFileAttributes.
                ///

                SHGFI_USEFILEATTRIBUTES = 0x000000010
            }

            ///
            ///     Creates an array of handles to large or small icons extracted from
            ///     the specified executable file, dynamic-link library (DLL), or icon
            ///     file.
            ///

            ///
            ///     Name of an executable file, DLL, or icon file from which icons will
            ///     be extracted.
            ///
            ///
            ///    
            ///         Specifies the zero-based index of the first icon to extract. For
            ///         example, if this value is zero, the function extracts the first
            ///         icon in the specified file.
            ///    

            ///    
            ///         If this value is �1 and and
            ///         are both NULL, the function returns
            ///         the total number of icons in the specified file. If the file is an
            ///         executable file or DLL, the return value is the number of
            ///         RT_GROUP_ICON resources. If the file is an .ico file, the return
            ///         value is 1.
            ///    

            ///    
            ///         Windows 95/98/Me, Windows NT 4.0 and later: If this value is a
            ///         negative number and either or
            ///         is not NULL, the function begins by
            ///         extracting the icon whose resource identifier is equal to the
            ///         absolute value of . For example, use -3
            ///         to extract the icon whose resource identifier is 3.
            ///    

            ///
            ///
            ///     An array of icon handles that receives handles to the large icons
            ///     extracted from the file. If this parameter is NULL, no large icons
            ///     are extracted from the file.
            ///
            ///
            ///     An array of icon handles that receives handles to the small icons
            ///     extracted from the file. If this parameter is NULL, no small icons
            ///     are extracted from the file.
            ///
            ///
            ///     Specifies the number of icons to extract from the file.
            ///
            ///
            ///     If the parameter is -1, the
            ///     parameter is NULL, and the
            ///     parameter is NULL, then the return
            ///     value is the number of icons contained in the specified file.
            ///     Otherwise, the return value is the number of icons successfully
            ///     extracted from the file.
            ///

            [DllImport("Shell32", CharSet = CharSet.Auto)]
            extern static int ExtractIconEx(
                [MarshalAs(UnmanagedType.LPTStr)]
            string lpszFile,
                int nIconIndex,
                IntPtr[] phIconLarge,
                IntPtr[] phIconSmall,
                int nIcons);

            [DllImport("Shell32", CharSet = CharSet.Auto)]
            extern static IntPtr SHGetFileInfo(
                string pszPath,
                int dwFileAttributes,
                out SHFILEINFO psfi,
                int cbFileInfo,
                FileInfoFlags uFlags);

            #endregion

            ///
            /// Two constants extracted from the FileInfoFlags, the only that are
            /// meaningfull for the user of this class.
            ///

            public enum SystemIconSize : int
            {
                Large = 0x000000000,
                Small = 0x000000001
            }

            ///
            /// Get the number of icons in the specified file.
            ///

            /// Full path of the file to look for.
            ///
            static int GetIconsCountInFile(string fileName)
            {
                return ExtractIconEx(fileName, -1, null, null, 0);
            }

            #region ExtractIcon-like functions

            public static void ExtractEx(string fileName, List largeIcons,
                List smallIcons, int firstIconIndex, int iconCount)
            {
                /*
                 * Memory allocations
                 */

                IntPtr[] smallIcOnsPtrs= null;
                IntPtr[] largeIcOnsPtrs= null;

                if (smallIcons != null)
                {
                    smallIcOnsPtrs= new IntPtr[iconCount];
                }
                if (largeIcons != null)
                {
                    largeIcOnsPtrs= new IntPtr[iconCount];
                }

                /*
                 * Call to native Win32 API
                 */

                int apiResult = ExtractIconEx(fileName, firstIconIndex, largeIconsPtrs, smallIconsPtrs, iconCount);
                if (apiResult != iconCount)
                {
                    throw new UnableToExtractIconsException(fileName, firstIconIndex, iconCount);
                }

                /*
                 * Fill lists
                 */

                if (smallIcons != null)
                {
                    smallIcons.Clear();
                    foreach (IntPtr actualIconPtr in smallIconsPtrs)
                    {
                        smallIcons.Add(Icon.FromHandle(actualIconPtr));
                    }
                }
                if (largeIcons != null)
                {
                    largeIcons.Clear();
                    foreach (IntPtr actualIconPtr in largeIconsPtrs)
                    {
                        largeIcons.Add(Icon.FromHandle(actualIconPtr));
                    }
                }
            }

            public static List ExtractEx(string fileName, SystemIconSize size,
                int firstIconIndex, int iconCount)
            {
                List icOnList= new List();

                switch (size)
                {
                    case SystemIconSize.Large:
                        ExtractEx(fileName, iconList, null, firstIconIndex, iconCount);
                        break;

                    case SystemIconSize.Small:
                        ExtractEx(fileName, null, iconList, firstIconIndex, iconCount);
                        break;

                    default:
                        throw new ArgumentOutOfRangeException("size");
                }

                return iconList;
            }

            public static void Extract(string fileName, List largeIcons, List smallIcons)
            {
                int icOnCount= GetIconsCountInFile(fileName);
                ExtractEx(fileName, largeIcons, smallIcons, 0, iconCount);
            }

            public static List Extract(string fileName, SystemIconSize size)
            {
                int icOnCount= GetIconsCountInFile(fileName);
                return ExtractEx(fileName, size, 0, iconCount);
            }

            public static Icon ExtractOne(string fileName, int index, SystemIconSize size)
            {
                try
                {
                    List icOnList= ExtractEx(fileName, size, index, 1);
                    return iconList[0];
                }
                catch (UnableToExtractIconsException)
                {
                    throw new IconNotFoundException(fileName, index);
                }
            }

            public static void ExtractOne(string fileName, int index,
                out Icon largeIcon, out Icon smallIcon)
            {
                List smallIcOnList= new List();
                List largeIcOnList= new List();
                try
                {
                    ExtractEx(fileName, largeIconList, smallIconList, index, 1);
                    largeIcon = largeIconList[0];
                    smallIcon = smallIconList[0];
                }
                catch (UnableToExtractIconsException)
                {
                    throw new IconNotFoundException(fileName, index);
                }
            }

            #endregion

            //this will look throw the registry
            //to find if the Extension have an icon.
            public static Icon IconFromExtension(string extension,
                                                    SystemIconSize size)
            {
                // Add the '.' to the extension if needed
                if (extension[0] != '.') extension = '.' + extension;

                //opens the registry for the wanted key.
                RegistryKey Root = Registry.ClassesRoot;
                RegistryKey ExtensiOnKey= Root.OpenSubKey(extension);
                ExtensionKey.GetValueNames();
                RegistryKey ApplicatiOnKey=
                    Root.OpenSubKey(ExtensionKey.GetValue("").ToString());

                //gets the name of the file that have the icon.
                string IcOnLocation=
                    ApplicationKey.OpenSubKey("DefaultIcon").GetValue("").ToString();
                string[] IcOnPath= IconLocation.Split(',');

                if (IconPath[1] == null) IconPath[1] = "0";
                IntPtr[] Large = new IntPtr[1], Small = new IntPtr[1];

                //extracts the icon from the file.
                ExtractIconEx(IconPath[0],
                    Convert.ToInt16(IconPath[1]), Large, Small, 1);
                return size == SystemIconSize.Large ?
                    Icon.FromHandle(Large[0]) : Icon.FromHandle(Small[0]);
            }

            public static Icon IconFromExtensionShell(string extension, SystemIconSize size)
            {
                //add '.' if nessesry
                if (extension[0] != '.') extension = '.' + extension;

                //temp struct for getting file shell info
                SHFILEINFO fileInfo = new SHFILEINFO();

                SHGetFileInfo(
                    extension,
,
                    out fileInfo,
                    Marshal.SizeOf(fileInfo),
                    FileInfoFlags.SHGFI_ICON | FileInfoFlags.SHGFI_USEFILEATTRIBUTES | (FileInfoFlags)size);

                return Icon.FromHandle(fileInfo.hIcon);
            }

            public static Icon IconFromResource(string resourceName)
            {
                Assembly assembly = Assembly.GetCallingAssembly();

                return new Icon(assembly.GetManifestResourceStream(resourceName));
            }

            ///
            /// Parse strings in registry who contains the name of the icon and
            /// the index of the icon an return both parts.
            ///

            /// The full string in the form "path,index" as found in registry.
            /// The "path" part of the string.
            /// The "index" part of the string.
            public static void ExtractInformationsFromRegistryString(
                string regString, out string fileName, out int index)
            {
                if (regString == null)
                {
                    throw new ArgumentNullException("regString");
                }
                if (regString.Length == 0)
                {
                    throw new ArgumentException("The string should not be empty.", "regString");
                }

                index = 0;
                string[] strArr = regString.Replace("\"", "").Split(',');
                fileName = strArr[0].Trim();
                if (strArr.Length > 1)
                {
                    int.TryParse(strArr[1].Trim(), out index);
                }
            }

            public static Icon ExtractFromRegistryString(string regString, SystemIconSize size)
            {
                string fileName;
                int index;
                ExtractInformationsFromRegistryString(regString, out fileName, out index);
                return ExtractOne(fileName, index, size);
            }
        }
    }
}       

代码如下:

///
        /// 应用程序的主入口点。
        ///

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            PictureBox pict = new PictureBox();
            pict.Image = BlackFox.Win32.Icons.IconFromExtension(".zip", BlackFox.Win32.Icons.SystemIconSize.Large).ToBitmap();
            pict.Dock = DockStyle.Fill;
            pict.SizeMode = PictureBoxSizeMode.CenterImage;

            Form form = new Form();
            form.Controls.Add(pict);
            Application.Run(form);
        }


推荐阅读
  • 本文详细介绍了GetModuleFileName函数的用法,该函数可以用于获取当前模块所在的路径,方便进行文件操作和读取配置信息。文章通过示例代码和详细的解释,帮助读者理解和使用该函数。同时,还提供了相关的API函数声明和说明。 ... [详细]
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • 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,并解决一些常见的配置问题。 ... [详细]
  • 电脑公司win7剪切板位置及使用方法
    本文介绍了电脑公司win7剪切板的位置和使用方法。剪切板一般位于c:\windows\system32目录,程序名为clipbrd.exe。通过在搜索栏中输入cmd打开命令提示符窗口,并输入clip /?即可调用剪贴板查看器。赶紧来试试看吧!更多精彩文章请关注本站。 ... [详细]
author-avatar
mobiledu2502908043
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有