欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-18 23:12:40
复制代码 代码如下:using system;using system.collections.generic;using system.text;namespace wi...

复制代码 代码如下:

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

上一篇:

下一篇: