sharptooth
sharptooth

Reputation: 170509

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?

Upvotes: 5

Views: 1243

Answers (2)

Anonymous
Anonymous

Reputation: 17

this is what you are for ...

using System;
using System.Drawing;
using System.Windows.Media;
using System.Runtime.InteropServices;

private BitmapSource Bmp2BmpSrc(Bitmap bitmap)
{
    IntPtr hBitmap = bitmap.GetHbitmap();
    BitmapSource bs;

    try
    {
        bs = Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

    }   finally { DeleteObject(hBitmap); } 

    return bs;
}

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);

hBitmap must be manually disposed of; otherwise, each call continues to consume memory until none is left. Apologies to the original content creator, I cannot find the link to the page I derived this from at the time.

Cheers

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613352

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.

Upvotes: 5

Related Questions