使用API获取Windows系统的文件关联图标
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
使用API获取Windows系统的文件关联图标
热推产品
- ActiveReport... 强大的.NET报表设计、浏览、打印、转换控件,可以同时用于WindowsForms谀坔攀戀Forms平台下......
- AnyChart AnyChart使你可以创建出绚丽的交互式的Flash和HTML5的图表和仪表控件。可以用于仪表盘的创......
推荐产品