-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathShellIcon.cs
89 lines (76 loc) · 2.82 KB
/
ShellIcon.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using System.IO;
namespace Herring
{
/// <summary>
/// Summary description for ShellIcon. Get a small or large Icon with an easy C# function call
/// that returns a 32x32 or 16x16 System.Drawing.Icon depending on which function you call
/// either GetSmallIcon(string fileName) or GetLargeIcon(string fileName)
/// </summary>
public static class ShellIcon
{
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
[DllImport("User32.dll")]
public static extern int DestroyIcon(IntPtr hIcon);
}
static ShellIcon()
{
}
public static Icon GetSmallIcon(string fileName)
{
return GetIcon(fileName, Win32.SHGFI_SMALLICON);
}
public static Icon GetLargeIcon(string fileName)
{
Icon result = GetIcon(fileName, Win32.SHGFI_LARGEICON);
return result;
}
private static Icon GetIcon(string fileName, uint flags)
{
if (File.Exists(fileName) == false)
{
return null;
}
SHFILEINFO shinfo = new SHFILEINFO();
IntPtr hImgSmall = Win32.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | flags);
if (shinfo.hIcon == IntPtr.Zero)
{
return null;
}
else
{
Icon icon = (Icon)System.Drawing.Icon.FromHandle(shinfo.hIcon).Clone();
Win32.DestroyIcon(shinfo.hIcon);
return icon;
}
}
public static Bitmap ConvertIconToBitmap(Icon icon)
{
Bitmap bmp = new Bitmap(icon.Size.Width, icon.Size.Height);
using (Graphics g = Graphics.FromImage(bmp))
g.DrawIcon(icon, 0, 0);
return bmp;
}
}
}