Convert System.Drawing.Icon to System.Media.ImageSource Convert System.Drawing.Icon to System.Media.ImageSource windows windows

Convert System.Drawing.Icon to System.Media.ImageSource


Simple conversion method without creating any extra objects:

    public static ImageSource ToImageSource(this Icon icon)    {        ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(            icon.Handle,            Int32Rect.Empty,            BitmapSizeOptions.FromEmptyOptions());        return imageSource;    }


Try this:

Icon img;Bitmap bitmap = img.ToBitmap();IntPtr hBitmap = bitmap.GetHbitmap();ImageSource wpfBitmap =     Imaging.CreateBitmapSourceFromHBitmap(          hBitmap, IntPtr.Zero, Int32Rect.Empty,           BitmapSizeOptions.FromEmptyOptions());

UPDATE: Incorporating Alex's suggestion and making it an extension method:

internal static class IconUtilities{    [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 you can do:

ImageSource wpfBitmap = img.ToImageSource();


When using disposable streams it is almost always recommended to use 'using' blocks to force correct releasing of resources.

using (MemoryStream iconStream = new MemoryStream()){   icon.Save(iconStream);   iconStream.Seek(0, SeekOrigin.Begin);   this.TargetWindow.Icon = System.Windows.Media.Imaging.BitmapFrame.Create(iconStream);}

Whereicon is the source System.Drawing.Icon, and this.TargetWindow is the target System.Windows.Window.