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

/// <summary>
            /// Contains information about a file object.
            /// </summary>
            struct SHFILEINFO
            {
                /// <summary>
                /// Handle to the icon that represents the file. You are responsible for
                /// destroying this handle with DestroyIcon when you no longer need it.
                /// </summary>
                public IntPtr hIcon;

/// <summary>
                /// Index of the icon image within the system image list.
                /// </summary>
                public IntPtr iIcon;

/// <summary>
                /// Array of values that indicates the attributes of the file object.
                /// For information about these values, see the IShellFolder::GetAttributesOf
                /// method.
                /// </summary>
                public uint dwAttributes;

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

/// <summary>
                /// String that describes the type of file.
                /// </summary>
                [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
                public string szTypeName;
            };

[Flags]
            enum FileInfoFlags : int
            {
                /// <summary>
                /// 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.
                /// </summary>
                SHGFI_ICON = 0x000000100,
                /// <summary>
                /// 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.
                /// </summary>
                SHGFI_USEFILEATTRIBUTES = 0x000000010
            }

/// <summary>
            ///     Creates an array of handles to large or small icons extracted from
            ///     the specified executable file, dynamic-link library (DLL), or icon
            ///     file.
            /// </summary>
            /// <param name="lpszFile">
            ///     Name of an executable file, DLL, or icon file from which icons will
            ///     be extracted.
            /// </param>
            /// <param name="nIconIndex">
            ///     <para>
            ///         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.
            ///     </para>
            ///     <para>
            ///         If this value is �1 and <paramref name="phiconLarge"/> and
            ///         <paramref name="phiconSmall"/> 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.
            ///     </para>
            ///     <para>
            ///         Windows 95/98/Me, Windows NT 4.0 and later: If this value is a
            ///         negative number and either <paramref name="phiconLarge"/> or
            ///         <paramref name="phiconSmall"/> is not NULL, the function begins by
            ///         extracting the icon whose resource identifier is equal to the
            ///         absolute value of <paramref name="nIconIndex"/>. For example, use -3
            ///         to extract the icon whose resource identifier is 3.
            ///     </para>
            /// </param>
            /// <param name="phIconLarge">
            ///     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.
            /// </param>
            /// <param name="phIconSmall">
            ///     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.
            /// </param>
            /// <param name="nIcons">
            ///     Specifies the number of icons to extract from the file.
            /// </param>
            /// <returns>
            ///     If the <paramref name="nIconIndex"/> parameter is -1, the
            ///     <paramref name="phIconLarge"/> parameter is NULL, and the
            ///     <paramref name="phiconSmall"/> 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.
            /// </returns>
            [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

/// <summary>
            /// Two constants extracted from the FileInfoFlags, the only that are
            /// meaningfull for the user of this class.
            /// </summary>
            public enum SystemIconSize : int
            {
                Large = 0x000000000,
                Small = 0x000000001
            }

/// <summary>
            /// Get the number of icons in the specified file.
            /// </summary>
            /// <param name="fileName">Full path of the file to look for.</param>
            /// <returns></returns>
            static int GetIconsCountInFile(string fileName)
            {
                return ExtractIconEx(fileName, -1, null, null, 0);
            }

#region ExtractIcon-like functions

public static void ExtractEx(string fileName, List<Icon> largeIcons,
                List<Icon> 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<Icon> ExtractEx(string fileName, SystemIconSize size,
                int firstIconIndex, int iconCount)
            {
                List<Icon> iconList = new List<Icon>();

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<Icon> largeIcons, List<Icon> smallIcons)
            {
                int iconCount = GetIconsCountInFile(fileName);
                ExtractEx(fileName, largeIcons, smallIcons, 0, iconCount);
            }

public static List<Icon> 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<Icon> 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<Icon> smallIconList = new List<Icon>();
                List<Icon> largeIconList = new List<Icon>();
                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));
            }

/// <summary>
            /// Parse strings in registry who contains the name of the icon and
            /// the index of the icon an return both parts.
            /// </summary>
            /// <param name="regString">The full string in the form "path,index" as found in registry.</param>
            /// <param name="fileName">The "path" part of the string.</param>
            /// <param name="index">The "index" part of the string.</param>
            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);
            }
        }
    }
}

代码如下:

/// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [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);
        }

(0)

相关推荐

  • C#中如何获取文件图标

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

  • C#程序最小化到托盘图标操作步骤与实现代码

    复制代码 代码如下: // this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged); //上面一行是主窗体InitializeComponent()方法中需要添加的引用 private void Form1_SizeChanged(object sender, EventArgs e) { if (this.WindowState==FormWindowState.Minimized) { this.Hide();

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

    事情是这样子的.我需要做一个下面的东东: 这个不难啊,然后就用FolderBrowerDialog这个神器,嗯 还不错,刚开始客户用了也很喜欢. 可是过了一段时间之后,客户说 要屏蔽右键功能,他不想让其他通过右键能打开或浏览文件夹,如下面 红色要给屏蔽. 我一开始以为只是一个参数问题,就爽快的答应了客户咯.可是啊后来找啊找 找到天荒地老也木有找到...放弃了,然后改用了TreeView..结果,版本出来了,先截图: 好吧,确实很丑哦.. 复制代码 代码如下: public MyDirectory

  • 用 C# 编写一个停放在任务栏上的图标程序

    用 C# 编写一个停放在任务栏上的图标程序  作者: 蔡世友 类别: C#/VB 日期: 2002-1-30 10:21:46   01-12-6 上午 10:53:11 -------------------------------------------------------------------------------- 引 言  C#语言是微软公司针对.Net平台才推出来的一门新语言,作为.Net平台的第一语言,它几乎集中了所有关于软件开发和软件工程研究的最新成果.其是当前第一个完全

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

  • JavaScript数组类型Array相关的属性与方法详解

    Array数组类型详解 在ECMAScript中除了object类型之外,Array数组用的是最常用的类型.ECMAScript数组可以在每一项存储任何类型的值,无需指定数组的长度,还可以随着数据的增长来增加数组长度,这些是和其他语言的数组不同的. 1.数组的创建方法 数组字面量方式 var arr = [1,2,3,4,5];// 简单直接用中括号包裹构建数组 数组构造函数 var arr = new Array(1,2,3,4,5);// 通过内置Array对象构建数组 2.检测数组 ins

  • C#调用Rar文件及获取Rar返回值的方法

    本文实例讲述了C#调用Rar文件及获取Rar返回值的方法.分享给大家供大家参考.具体如下: 该程序适用于C#调用. 所需的Rar.exe可从WinRar官网下载控制台版. 按钮OK点击事件: System.Diagnostics.Process process; private void btnRAR_Click(object sender, EventArgs e) { if (System.IO.File.Exists("Rar.exe")) { try { process = n

  • MySQL下PID文件丢失的相关错误的解决方法

    今天同事A找到我,说是Mysql server X的负载很高,查询很慢.他自己捣鼓了一阵未果后,我们一起看了下. [root@redhat var]# uname -a Linux xxx 2.6.18-128.el5 #1 SMP Wed Dec 17 11:41:38 EST 2008 x86_64 x86_64 x86_64 GNU/Linux [root@redhat var]# mysql -u root -p -e "select version();" +--------

  • javascript获取选中的文本的方法代码

    复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title> new document

  • iOS获取网络类型的方法汇总

    Reachability类只能区分WIFI和WWAN类型,却无法区分2G网和3G网. 网上也有些方法,却都存在Bug. 经过网上查找资料和测试,基本上总结了以下几种方法: 1.使用导航栏的方式:(私有API) 代码: 复制代码 代码如下: typedef enum {     NetWorkType_None = 0,     NetWorkType_WIFI,     NetWorkType_2G,     NetWorkType_3G, } NetWorkType; UIApplicatio

  • asp.net 下载文件时根据MIME类型自动判断保存文件的扩展名

    引言 用WebClient下载远程资源时,经常会遇到类似这样的网址: http://www.uushare.com/filedownload?user=icesee&id=2205188 http://www.guaishow.com/u/luanfujie/g9675/ 我们不知道这个Url具体代表的是一个网页,还是某种类型的文件. 而有些Url虽然带有扩展名,但可能是错误的扩展名,常见的比如把gif文件标上了jpg扩展名. 如果我们没法正确判断下载源的文件类型的话,就无法保存为正确的文件格式

  • Python判断文件和字符串编码类型的实例

    python判断文件和字符串编码类型可以用chardet工具包,可以识别大多数的编码类型.但是前几天在读取一个Windows记事本保存的txt文件时,GBK却被识别成了KOI8-R,无解. 然后就自己写了个简单的编码识别方法,代码如下: coding.py # 说明:UTF兼容ISO8859-1和ASCII,GB18030兼容GBK,GBK兼容GB2312,GB2312兼容ASCII CODES = ['UTF-8', 'UTF-16', 'GB18030', 'BIG5'] # UTF-8 B

  • Python把对应格式的csv文件转换成字典类型存储脚本的方法

    该脚本是为了结合之前的编写的脚本,来实现数据的比对模块,实现数据的自动化!由于数据格式是定死的,该代码只做参考,有什么问题可以私信我! CSV的数据格式截图如下: readDataToDic.py源代码如下: #coding=utf8 import csv ''' 该模块的主要功能,是根据已有的csv文件, 通过readDataToDicl函数,把csv中对应的部分, 写入字典中,每个字典当当作一条json数据 ''' class GenExceptData(object): def __ini

  • 微信小程序获取网络类型的方法示例 原创

    本文实例讲述了微信小程序获取网络类型的方法.分享给大家供大家参考,具体如下: 这里主要演示通过wx.getNetworkType获取当前网络类型的操作方法.代码如下: index.js: Page({ /** * 页面的初始数据 */ data: { netType:'' }, /** * 生命周期函数--监听页面加载 */ onLoad: function () { var that = this; try { wx.getNetworkType({ success: function(res

随机推荐