Search code examples
c#.netbitmappinvokehbitmap

How do I have DeleteObject() invoked on hBitmap other than by using P/Invoke?


I'm dealing with code that goes something like this (from here)

using (var bmp = new System.Drawing.Bitmap(1000, 1000)) 
{
    IntPtr hBitmap = bmp.GetHbitmap(); 
    var source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        hBitmap, IntPtr.Zero, Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}

and MSDN says that whenever I call Bitmap.GetHbitmap() I have to call DeleteObject() on the hBitmap to release the unmanaged resources.

All the answers I've seen and MSDN say I have to P/Invoke the DeleteObject() function. This looks a bit insane because I obtained the hBitmap without P/Invoke and now I suddenly need to use P/Invoke to proper get rid of it.

Is there indeed no other way except P/Invoke to have DeleteObject() called for my hBitmap?


Solution

  • I don't think that there's any way to call DeleteObject from C# other than using p/invoke.

    So, if you want to avoid this undesired trip into unmanaged code then you should avoid calling GetHbitmap in the first place. You can do that readily enough. You want to make a BitmapSource. Do that with a call to BitmapSource.Create.