Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All, I'm trying to declare a CPen object in class scope and using it in OnDraw(...).But my application is crashing when I run it.If I declare the object in OnDraw(...) it is working fine. Can anyone please let me know do I need to any extra thing if declare CPen object in class scope? Thanks in advance.

What I have tried:

C++
xxxxx.h
private:
  CPen cPen;


xxxxx.cpp

void CMFCApplication2View::OnDraw(CDC* pDC)
{
        //CPen cPen;  If I do it here its working fine.
	CPen* pOldPen = NULL;

	BOOL bCPen = cPen.CreatePen(PS_SOLID, 10, RGB(255, 0, 0));

	
	if (bCPen)
	{
		pOldPen = pDC->SelectObject(&cPen);

		pDC->MoveTo(95, 125);
		pDC->LineTo(230, 125);

		pDC->SelectObject(pOldPen);
		//cPen.DeleteObject();
	}
}
Posted
Updated 26-Jul-16 18:28pm
v4
Comments
Richard MacCutchan 27-Jul-16 3:52am    
Run the code through the debugger to see exactly where it crashes and which variable is causing the problem.

You are calling CreatePen again and again with each drawing.

The simplest solution would be calling CreatePen in the constructor of your class and remove it from the draw function:
C++
CMFCApplication2View::CMFCApplication2View()
{
    // Other initialisation goes here

    cPen.CreatePen(PS_SOLID, 10, RGB(255, 0, 0));
}

void CMFCApplication2View::OnDraw(CDC* pDC)
{
    CPen* pOldPen = pDC->SelectObject(&cPen);

    // Perform drawing here

    pDC->SelectObject(pOldPen);
}
 
Share this answer
 
Comments
cppcoder1 27-Jul-16 0:25am    
Thanks Jochen Arndt, But it's not solving my problem.Its crashing when I create Cpen object in class scope
Jochen Arndt 27-Jul-16 2:59am    
Are you sure that the crash occurs when calling CreatePen() in the constructor? That is rather unlikely.

What kind of crash is it? Are you using a debug build and start the application within the debugger?
C++
BOOL CPen = cPen.CreatePen(PS_SOLID, 10, RGB(255, 0, 0));

What on earth is that statement supposed to be? You are redeclaring a class name (CPen) as a BOOLean variable.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900