14

I want to set a background image for my form/window like this guy but instead of an image file on disk I've got a System.Drawing.Bitmap in memory.

I need to do something like this:

this.Background = new ImageBrush(new BitmapImage(bmp));

Except BitmapImage won't take a Bitmap, nor will ImageBrush and I'm not sure if any of the others will. There's one called BitmapCacheBrush but I don't know what that does.

1 Answer 1

18

Nevermind, I figured it out.

public static Brush CreateBrushFromBitmap(Bitmap bmp)
{
    return new ImageBrush(Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()));
}

credit

1
  • 2
    You'll need to import and P/Invoke DeleteObject on that handle from Bitmap.GetHBitmap() or you'll be leaking GDI handles. Refer to the documentation for more info.
    – Alan
    Commented Jul 18, 2014 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.