结合Krzysztof Kowalczyk的回答和一些搜索,我想出了以下内容:
方法:
public static ImageSource GetIcon(string strPath, bool bSmall)
{
Interop.SHFILEINFO info = new Interop.SHFILEINFO(true);
int cbFileInfo = Marshal.SizeOf(info);
Interop.SHGFI flags;
if (bSmall)
flags = Interop.SHGFI.Icon | Interop.SHGFI.SmallIcon | Interop.SHGFI.UseFileAttributes;
else
flags = Interop.SHGFI.Icon | Interop.SHGFI.LargeIcon | Interop.SHGFI.UseFileAttributes;
Interop.SHGetFileInfo(strPath, 256, out info, (uint)cbFileInfo, flags);
IntPtr iconHandle = info.hIcon;
ImageSource img = Imaging.CreateBitmapSourceFromHIcon(
iconHandle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
Interop.DestroyIcon(iconHandle);
return img;
}
以及Interop类:
using System;
using System.Runtime.InteropServices;
public static class Interop
{
private const int MAX_PATH = 260;
private const int MAX_TYPE = 80;
[Flags]
public enum SHGFI : int
{
Icon = 0x000000100,
DisplayName = 0x000000200,
TypeName = 0x000000400,
Attributes = 0x000000800,
IconLocation = 0x000001000,
ExeType = 0x000002000,
SysIconIndex = 0x000004000,
LinkOverlay = 0x000008000,
Selected = 0x000010000,
Attr_Specified = 0x000020000,
LargeIcon = 0x000000000,
SmallIcon = 0x000000001,
OpenIcon = 0x000000002,
ShellIconSize = 0x000000004,
PIDL = 0x000000008,
UseFileAttributes = 0x000000010,
AddOverlays = 0x000000020,
OverlayIndex = 0x000000040,
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHFILEINFO
{
public SHFILEINFO(bool b)
{
hIcon = IntPtr.Zero;
iIcon = 0;
dwAttributes = 0;
szDisplayName = "";
szTypeName = "";
}
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_TYPE)]
public string szTypeName;
};
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
public static extern int SHGetFileInfo(
string pszPath,
int dwFileAttributes,
out SHFILEINFO psfi,
uint cbfileInfo,
SHGFI uFlags);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool DestroyIcon(IntPtr hIcon);
}
源代码
icon.ToBitmap()
,你可以直接将图标转换为 ImageSource,使用icon.Handle
属性和 Thomas 或 Krysztof 的答案。或者参考 这里。 - Dzyann