windows C#:如何获取某个文件的图标?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2160923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: How can I get the icon for a certain file?
提问by Svish
If I have the path to a file, is there a way I can get the icon that windows would have displayed for that file in Windows Explorer?
如果我有文件的路径,有没有办法在 Windows 资源管理器中获取 Windows 为该文件显示的图标?
回答by Sam Harwell
First of all, there are multiple sizes of images, some of which are easier to get than others. If you want the "normal" size one (I believe 32x32) and can use WPF (referencing PresentationCore), this is a great way to do it:
首先,图像有多种尺寸,其中一些比其他更容易获得。如果您想要“正常”尺寸(我相信 32x32)并且可以使用 WPF(参考 PresentationCore),这是一个很好的方法:
public System.Windows.Media.ImageSource Icon
{
get
{
if (icon == null && System.IO.File.Exists(Command))
{
using (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(Command))
{
// This new call in WPF finally allows us to read/display 32bit Windows file icons!
icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
sysicon.Handle,
System.Windows.Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
}
return icon;
}
}
回答by Keith Maurino
System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(filePath);