How to convert WinForms Bitmap to WPF ImageSource

If by chance you’re progressively migrating a legacy WinForms application to WPF, at some point you’ll have to use existing bitmaps and convert them to the WPF equivalent one.

It seems this is a FAQ in the forums, and some of the solutions that I saw that use the System.Windows.Interop namespace, have memory leak issues. When creating a GDI bitmap object, we must release its memory as soon as possible and people are missing this important step.

That said, I’ve decided to share the following code snippet that you can use to convert a Bitmap to an ImageSource.

public static class BitmapExtensions
{
    public static ImageSource ToImageSource(this Bitmap bitmap)
    {
        var hbitmap = bitmap.GetHbitmap();
        try
        {
            var imageSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bitmap.Width, bitmap.Height));

            return imageSource;
        }
        finally
        {
            NativeMethods.DeleteObject(hbitmap);
        }
    }
}

public static class NativeMethods
{
    [DllImport("gdi32")]
    public static extern int DeleteObject(IntPtr hObject);
}

Shout it

How to get Design Mode property in WPF

Last day I needed to check if the code was executing in Design Mode but I couldn’t remember how to do it, so I had to Google again for that matter. That said, I decided to blog about it to prevent wasting my time in a near future.

Jim Nakashima has a nice post about the subject, you can read it here, so I wont get into much detail.

The code to get the design mode property in your control looks like this:

using System.ComponentModel;

private bool IsInDesignMode
{
    get
    {
        return DesignerProperties.GetIsInDesignMode(this);
    }
}

If you don’t have a DependencyObject you can still get the property using the following:

using System.ComponentModel;

private bool IsInDesignMode
{
    get
    {
        return DesignerProperties.GetIsInDesignMode(new DependencyObject());
    }
}

or

using System.ComponentModel;

private bool IsInDesignMode
{
    get
    {
        return (bool)DesignerProperties.IsInDesignModeProperty
            .GetMetadata(typeof(DependencyObject)).DefaultValue;
    }
}

Shout it