Show icon in wpf Image

I have a wpf application that should extract an icon from an executable file. I found here that I can do this

Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName); 

but when I try to set the wpf Image source, I get "Cannot implicitly convert the type" System.Drawing.Icon "to" System.Windows.Media.ImageSource "

Any suggestions?

+4
source share
3 answers

Icons are not liked in the .NET Framework. You will need to use Icon.Save () to save the icon you received in the MemoryStream. This allows you to use the IconBitmapDecoder constructor, which accepts the stream.

+6
source

I had a similar problem, and in a few steps we can get the image source:

 ImageSource imageSource; Icon icon = Icon.ExtractAssociatedIcon(path); using (Bitmap bmp = icon.ToBitmap()) { var stream = new MemoryStream(); bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png); imageSource = BitmapFrame.Create(stream); } 

We can use this image source to supply a property source outside of XAML:

  <Image Source="{Binding Path=ImageSource, Mode=OneTime}" /> 
+5
source

I wanted to offer a solution that I came up with:

 public static class IconExtensions { [DllImport("gdi32.dll", SetLastError = true)] private static extern bool DeleteObject(IntPtr hObject); public static ImageSource ToImageSource(this Icon icon) { Bitmap bitmap = icon.ToBitmap(); IntPtr hBitmap = bitmap.GetHbitmap(); ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!DeleteObject(hBitmap)) { throw new Win32Exception(); } return wpfBitmap; } } 

Then I have an IconToImageSourceConverter that just calls the method above.

So that I can add icons as images, I added:

 <DataTemplate DataType="{x:Type drawing:Icon}"> <Image Source="{Binding Converter={converter:IconToImageSourceConverter}}" MaxWidth="{Binding Width}" MaxHeight="{Binding Height}"/> </DataTemplate> 

Thus, if the icon is placed directly in XAML, if it still displays:

 <x:Static MemberType="{x:Type drawing:SystemIcons}" Member="Asterisk"/> 

Otherwise, the converter can be used in place, for example:

 <Image Source="{Binding Source={x:Static drawing:SystemIcons.Asterisk}, Converter={converter:IconToImageSourceConverter}}"/> 
+3
source

Source: https://habr.com/ru/post/1311791/


All Articles