MFC Triangle Drawing in C++ Guide
When drawing a triangle using MFC, you can achieve this by overriding the OnPaint function of the CWnd class. The specific steps are as follows:
Firstly, create an MFC application and add a derived class from CWnd within it.
Add the following code to the header file of the CWnd class.
class CTriangleWnd : public CWnd
{
public:
CTriangleWnd();
virtual ~CTriangleWnd();
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnPaint();
};
3. Add the following code to the implementation file of the CWnd class:
BEGIN_MESSAGE_MAP(CTriangleWnd, CWnd)
ON_WM_PAINT()
END_MESSAGE_MAP()
CTriangleWnd::CTriangleWnd()
{
}
CTriangleWnd::~CTriangleWnd()
{
}
void CTriangleWnd::OnPaint()
{
CPaintDC dc(this);
// 绘制三角形
POINT points[3];
points[0] = { 100, 100 };
points[1] = { 150, 200 };
points[2] = { 50, 200 };
dc.Polygon(points, 3);
}
Create an instance of CTriangleWnd in the main window class and then display it.
BOOL CMyApp::InitInstance()
{
// 创建主窗口
CMainFrame* pFrame = new CMainFrame;
m_pMainWnd = pFrame;
// 创建三角形窗口
CTriangleWnd* pTriangleWnd = new CTriangleWnd;
pTriangleWnd->Create(NULL, _T("Triangle Window"), WS_VISIBLE | WS_OVERLAPPEDWINDOW, CRect(0, 0, 300, 300), pFrame);
// 显示主窗口
pFrame->ShowWindow(SW_SHOW);
pFrame->UpdateWindow();
return TRUE;
}
By following the above steps, you can use the CWnd class in MFC application to draw a simple triangle.