如何在C#项目中使用shell32.dll中的图像?
发布于 2011-07-29 20:25:17
您可以使用以下代码从DLL中提取图标:
public class IconExtractor
{
public static Icon Extract(string file, int number, bool largeIcon)
{
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try
{
return Icon.FromHandle(largeIcon ? large : small);
}
catch
{
return null;
}
}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);
}
...
form.Icon = IconExtractor.Extract("shell32.dll", 42, true);当然,您需要知道DLL中图像的索引...
发布于 2011-07-29 20:25:38
MSDN开发者论坛上的This thread提供了一个解决方案:
在.NET中实现这些的典型方法是使用位于C:\Program Files\Microsoft Visual Studio \Common7\VS200XImageLibrary的
文件中提供的图形。
您没有说明您安装了哪个版本的Visual Studio,但您需要将"200X“替换为您的版本号。
发布于 2020-06-22 04:44:49
接受应答中的代码在每次调用时都会泄漏一个图标句柄,因为它总是请求两个图标句柄,而只返回一个图标句柄。
下面是一个不会泄漏句柄的版本:
public static Icon Extract(string filePath, int index, bool largeIcon = true)
{
if (filePath == null)
throw new ArgumentNullException(nameof(filePath));
IntPtr hIcon;
if (largeIcon)
{
ExtractIconEx(filePath, index, out hIcon, IntPtr.Zero, 1);
}
else
{
ExtractIconEx(filePath, index, IntPtr.Zero, out hIcon, 1);
}
return hIcon != IntPtr.Zero ? Icon.FromHandle(hIcon) : null;
}
[DllImport("shell32", CharSet = CharSet.Unicode)]
private static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phiconLarge, IntPtr phiconSmall, int nIcons);
[DllImport("shell32", CharSet = CharSet.Unicode)]
private static extern int ExtractIconEx(string lpszFile, int nIconIndex, IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons);https://stackoverflow.com/questions/6872957
复制相似问题