我的wpf应用程序中有一个按钮和一个名为image1的图像。我想从位置或文件路径的文件图标添加image1的图像源。这是我的代码:
using System.Windows;
using System.Windows.Media.Imaging;
using System.IO;
using System.Drawing;
namespace WpfApplication2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe");
image1.Source = ico.ToBitmap();
}
}
}
错误是说
无法将类型'System.Drawing.Bitmap'隐式转换为'System.Windows.Media.ImageSource'
如何解决这个问题呢?
Farhan Anam提出的解决方案可以使用,但是并不理想:图标是从文件加载,转换为位图,保存到流并从流中重新加载的。那是相当低效的。
另一种方法是使用System.Windows.Interop.Imaging
类及其CreateBitmapSourceFromHIcon
方法:
private ImageSource IconToImageSource(System.Drawing.Icon icon)
{
return Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
new Int32Rect(0, 0, icon.Width, icon.Height),
BitmapSizeOptions.FromEmptyOptions());
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
using (var ico = System.Drawing.Icon.ExtractAssociatedIcon(@"C:\WINDOWS\system32\notepad.exe"))
{
image1.Source = IconToImageSource(ico);
}
}
请注意using
转换后的原始图标放置块。不这样做会导致手柄泄漏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句