Click to See Complete Forum and Search --> : Drawing using CDC on a WinForm


douda123
August 27th, 2010, 09:02 AM
Hi,

I have a question concerning MFC drawing on a WinForm. I have old drawing in MFC (using CDC) and I want to use that code to draw on a C# WinForm.


Here is the old MFC code:
---------------------------------------------------------------
void CMyDrawer :: Draw(CDC& dc)
{
dc.Rectangle(10, 10, 50, 60);
}
---------------------------------------------------------------

And here is the code in the wrapper DLL (mixed DLL) that I used to wrap the native code and make it usable in a C# assembly:

---------------------------------------------------------------
void CMyDrawerWrapper :: Draw(IntPtr handlePtr)
{
HDC hDC = static_cast<HDC>(handlePtr.ToPointer());

CDC dc;
dc.Attach(hDC);

CMyDrawer myDrawer
myDrawer.Draw(dc);
}
---------------------------------------------------------------

And finally this is the code I have in the C# WinForm:

---------------------------------------------------------------
private void Form1_Load(object sender, EventArgs e)
{
if (pictureBox1.Image == null)
{
pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
}

MyDrawerWrapperNamespace.CMyDrawerWrapper myDrawerWrapper = new MyDrawerWrapperNamespace.CMyDrawerWrapper();
myDrawerWrapper.Draw(pictureBox1.Handle);

}
---------------------------------------------------------------

Unfortunately the code is not drawing anything.. Is there anything I am missing?

Please advise.
Thanks in advance

Alex F
August 27th, 2010, 11:56 AM
You pass PictureBox handle instead of HDC. Correct way is to handle PictureBox paint avent.


private void pictureBox1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
Graphics g = e.Graphics;
IntPtr hdc = e.Graphics.GetHdc();
myDrawerWrapper.Draw(hdc);
e.Graphics.ReleaseHdc(hdc);
}

douda123
August 27th, 2010, 12:08 PM
Thanks Alex... You're brilliant!