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.

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

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

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 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 Jul 18 '14 at 18:40