Link to home
Start Free TrialLog in
Avatar of PMH4514
PMH4514

asked on

Why isn't my CPen working right?

This code draws a black rectangle with 1px lines on my DC, it should be drawing a 3px red rectangle. what's wrong?

      COLORREF penColor = RGB(255,0,0);
      CPen penRed;
      penRed.CreatePen(PS_SOLID, 3, penColor );
      CPen* pOldPen = (CPen*)SelectObject(hDC, &penRed);

      // create a null brush for un-filled rectange.
       CBrush pNullBrush;
       pNullBrush.CreateStockObject(NULL_BRUSH);

      CBrush * pOldBrush = (CBrush *)SelectObject(hDC, pNullBrush);

      RECT* rpBoxRect = new RECT;      // rectangle
      rpBoxRect->left = iLeft;      // temp hard-coded.. derive from INI map_size and window size values.
      rpBoxRect->top = iTop;      
      rpBoxRect->right = iRight;
      rpBoxRect->bottom = iBottom;

      // draw rectangle overlay.
      pDC->Rectangle(rpBoxRect);


???

thanks!
-Paul
ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The brush is used for "filling" the rectangle, while the pen is used for the frame.

To draw a red rectangle simply call

pDC->FillSolidRect( nLeft , nTop , nWidth , nHeight , RGB(255,0,0) );

You don't need to create no null brush, it's ready for you already in the dc

pDC->SelectStockObject( NULL_BRUSH );

Are you in MM_TEXT mode, use pDC->SetMapMode() to try it out. Are you sure you have got the right hDC, the device has two! Try GetSafeHdc() on the device context, or use the dc pointer instead like both Andy and I already did.

This worked for me:

CPen pp;
pp.CreatePen(PS_SOLID,3,RGB(255,0,0));
pDC->SelectObject(&pp);
pDC->SelectStockObject(NULL_BRUSH);
pDC->Rectangle( 10,10,40,40 );

Avatar of PMH4514
PMH4514

ASKER

I think maybe you misunderstood. I want to draw an unfilled rectangle (ie. the NULL_BRUSH) - drawn out of red lines. that is, an empty red box.

 I'll try your code chunk when I get to the office. thanks!

-paul
My comment should have identified and solved your problem.
Avatar of PMH4514

ASKER

AndyAinscow - yup, I actually just noticed your comment.. When I responded above, I had only seen the one from Ruskialt, I must have scrolled past it..

trying it right now...

beautiful.. it worked!

Could you kindly explain why mine didn't work?

Thanks!
-Paul
I suspect your hDC you used initially was not the hDC of the pDC.  Does that make sense?
The DC has two:

m_hDC
m_hAttribDC

But afaik you are safe using pDC-> instead. The dc will lead your command to the right handle..
Avatar of PMH4514

ASKER

Gotcha.  Thanks!

-Paul