站在巨人的肩上

Standing on Shoulders of Giants
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

使用API获取Windows系统的文件关联图标

Posted on 2011-05-04 14:32  姚箫  阅读(2916)  评论(0)    收藏  举报
 1        #region 读取文件图标
 2         [DllImport("shell32.dll")]
 3         static extern uint ExtractIconEx(string lpszFile, int nIconIndex, int[] phiconLarge, int[] phiconSmall, uint nIcons);
 4 
 5         /// <summary>
 6         /// 给出文件扩展名(.*),返回相应图标
 7         /// </summary>
 8         /// <param name="fileType">文件类型</param>
 9         /// <param name="isLarge">是否需要大图标,bool值</param>
10         /// <returns></returns>
11         Icon GetIconByFileType(string fileType, bool isLarge)
12         {
13 
14             if (fileType == null || fileType.Equals(string.Empty)) return null;
15 
16             RegistryKey regVersion = null;
17             string regFileType = null;
18             string regIconString = null;
19             string systemDirectory = Environment.SystemDirectory + "\\";
20 
21             if (fileType[0== '.')
22             {
23                 //读系统注册表中文件类型信息
24                 regVersion = Registry.ClassesRoot.OpenSubKey(fileType, true);
25                 if (regVersion != null)
26                 {
27                     regFileType = regVersion.GetValue(""as string;
28                     regVersion.Close();
29                     regVersion = Registry.ClassesRoot.OpenSubKey(regFileType + @"\DefaultIcon"true);
30                     if (regVersion != null)
31                     {
32                         regIconString = regVersion.GetValue(""as string;
33                         regVersion.Close();
34                     }
35                 }
36                 if (regIconString == null || regIconString.Length <= 0)
37                 {
38                     //没有读取到文件类型注册信息,指定为未知文件类型的图标
39                     regIconString = systemDirectory + "shell32.dll,0";
40                 }
41             }
42             else
43             {
44                 //直接指定为文件夹图标
45                 regIconString = systemDirectory + "shell32.dll,3";
46             }
47             string[] fileIcon = regIconString.Split(new char[] { ',' });
48             if (fileIcon.Length != 2)
49             {
50                 //系统注册表中注册的标图不能直接提取,则返回可执行文件的通用图标
51                 fileIcon = new string[] { systemDirectory + "shell32.dll""2" };
52             }
53             Icon resultIcon = null;
54             try
55             {
56                 //调用API方法读取图标
57                 int[] phiconLarge = new int[1];
58                 int[] phiconSmall = new int[1];
59                 uint count = ExtractIconEx(fileIcon[0], Int32.Parse(fileIcon[1]), phiconLarge, phiconSmall, 1);
60                 IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
61                 resultIcon = Icon.FromHandle(IconHnd);
62             }
63             catch { }
64             return resultIcon;
65         }
66         #endregion