0

Images in MFC are created in the OnDraw function. We have to give "pDC->m_hDC" as the parameter if we want to draw an image...

The problem is that we can get pDC only in our OnDraw function. Now if we want to draw images outside that OnDraw then we need to create a pointer to "CDC" type to get "m_hDC" from it.

Some people said use this code:

CDC * dc = getDC();

But it says getDC() is undefined. What should I do?

The main point is that I want an initialized pointer to CDC in order to use it anywhere.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
repoleved
  • 133
  • 2
  • 12

3 Answers3

1

Outside of the OnDraw function you can create a CDC with

CClientDC dc;

You very rarely need the m_hDC because CDC encapsulates almost all of the drawing functions. Like

dc.DrawIcon(x, y, m_hIcon);
ScottMcP-MVP
  • 10,337
  • 2
  • 15
  • 15
0

I commonly do something like this :

void CMyView::ForceRedraw()
{
    CClientDC pDC(this);
    OnDraw(&pDC);
}
Roger Rowland
  • 25,885
  • 11
  • 72
  • 113
  • Basically i am making a chess game. The method you said redraws the whole screen. This takes too much time i want to create a CDC pointer so that only the particular piece that is moved is printed not the whole board. Overall thanks for your Answer. – repoleved Jun 18 '14 at 09:32
  • @Mahroz You are approaching the problem from the wrong direction. To initiate a redraw of a portion of the screen you mark this area as invalid by calling [`CWnd::InvalidateRect`](http://msdn.microsoft.com/en-us/library/2f3csed3.aspx). In your `OnDraw`-handler you can check whether a particular piece needs to be rendered by retrieving the invalid area calling [`CWnd::GetUpdateRect`](http://msdn.microsoft.com/en-us/library/xb78w9y0.aspx). As an aside: You will fail understanding MFC if you do not know the Windows API. – IInspectable Jun 20 '14 at 23:06
0

Another a solution is to use:

CClientDC* pDC = new CClientDC(this);

If you wish to use CDC pointer.

Brian Bai
  • 15
  • 5