Search code examples
c#windowsbitmapgdi

Modifying a C# Bitmap in an external DLL


I need to process an image which is provided by a C# program as a Bitmap object. The processing is performed in a C++ DLL, which receives a handle to a GDI object (HBITMAP) created from the Bitmap, via

Bitmap.GetHbitmap();

The argument passing between C# and the DLL works fine, and the GDI object has the expected characteristics. I can read the pixels of the image, in the DLL.

Anyway, when I try to modify the image via the DLL, the change is not reflected in the C# application, as if the image was read-only. I suspect that some operation must be performed to convert back from the GDI object to the Bitmap instance, but I see nothing in the .NET API.

I am aware of the LockBits/UnlockBits mechanism, which I could probably use if nothing else works, but my current requirement is to pass a Handle only.

Any hint ?


Solution

  • What you are looking for is the Image.FromHbitmap() method. Using it you will be able to convert from a HBITMAP into a .NET Bitmap.

    Bitmap bmp = Image.FromHbitmap(<HBITMAP pointer here>);