6

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

  • 1
    Can you post the C# code you have tried? Is it different from [this GetHdc example](http://msdn.microsoft.com/en-us/library/9z5820hw(v=VS.80).aspx)? – PhilMY Jun 29 '12 at 12:21

1 Answers1

6

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.

Ivan Shcherbakov
  • 2,063
  • 14
  • 23