CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Aug 2010
    Posts
    14

    Drawing using CDC on a WinForm

    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

  2. #2
    Join Date
    Jul 2002
    Posts
    2,543

    Re: Drawing using CDC on a WinForm

    You pass PictureBox handle instead of HDC. Correct way is to handle PictureBox paint avent.

    Code:
    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);
    }

  3. #3
    Join Date
    Aug 2010
    Posts
    14

    Re: Drawing using CDC on a WinForm

    Thanks Alex... You're brilliant!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured