Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing on C# Bitmap with C++

I have a 3rd party dll (plain C++) which draws on a HDC some lines. I want to have these lines on a C# Bitmap or Form.

I tried to give the C++ a HBITMAP or a HDC of the Graphics.FromImage(bitmap) but none of the above ways worked for me.

With a MFC TestApp everything works fine using the following code

HWND handle = pStatic->GetSafeHwnd();
CDC* dc = pStatic->GetDC();

Draw(dc);

My question is: What do I have to do/use to draw on a Bitmap or form with the above Draw(HDC) method?

I hope you can help me. Thanks in advance,

Patrick

like image 367
Patrick Feistel Avatar asked Jun 29 '12 11:06

Patrick Feistel


1 Answers

To draw on a C# bitmap use this code:

        Graphics gr = Graphics.FromImage(MyBitmap);
        IntPtr hdc = gr.GetHdc();
        YourCPPDrawFunction(hdc);
        gr.ReleaseHdc(hdc);

An example of a YourCPPDrawFunction is:

    void YourCPPDrawFunction(HDC hDc)
    {
        SelectObject(hDc, GetStockObject(BLACK_PEN));
        Rectangle(hDc, 10, 10, 20, 20);
    }

To draw directly on a form surface, use this code:

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        IntPtr hdc = e.Graphics.GetHdc();
        YourCPPDrawFunction(hdc);
        e.Graphics.ReleaseHdc(hdc);
    }

Do not forget to call Graphics.ReleaseHdc() after you're done drawing, otherwise you won't see the results of your drawing.

like image 151
Ivan Shcherbakov Avatar answered Oct 20 '22 07:10

Ivan Shcherbakov