绘制简单的图形几乎是所有的VC教程中的必须内容,这里面涉及到几个概念,设备(device context),画刷(Pen)等。CDC是所有设备的父类,其子类包括CClientDC(仅在客户区绘制), CPaintDC, CWindowDC(可以在客户区和窗口非客户区绘制)等。所有继承于CWnd类的子类均可以构造设备类。
#include <afxwin.h>
class MFC_Tutorial_Window: public CFrameWnd
{
CPoint m_startPoint;
CPoint m_endPoint;
public:
MFC_Tutorial_Window()
{
Create(NULL, "MFC Tutorial");
}
void OnLButtonDown(UINT nFlags, CPoint point);
/* {
CFrameWnd::OnLButtonDown(nFlags,point);
m_startPoint = point;
}*/
void OnLButtonUp(UINT nFlags, CPoint point);
/* {
CFrameWnd::OnLButtonUp(nFlags, point);
m_endPoint = point;
CClientDC dc(this);
dc.MoveTo(m_startPoint);
dc.LineTo(m_endPoint);
}*/
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP( MFC_Tutorial_Window, CFrameWnd)
ON_WM_LBUTTONDOWN() //Macro to map the left button click to the handler
ON_WM_LBUTTONUP() //Macro to map the left button click to the handler
END_MESSAGE_MAP()
void MFC_Tutorial_Window::OnLButtonDown(UINT nFlags, CPoint point)
{
m_startPoint = point;
CFrameWnd::OnLButtonDown(nFlags,point);
}
void MFC_Tutorial_Window::OnLButtonUp(UINT nFlags, CPoint point)
{
m_endPoint = point;
CPen pen(PS_SOLID, 1, RGB(255,0,0));
CWindowDC dc(this); // 构造dc时必须传入一个CWnd类或其子类对象
CPen* pOldPen = dc.SelectObject(&pen);
dc.MoveTo(m_startPoint);
dc.LineTo(m_endPoint);
dc.SelectObject(pOldPen);
CFrameWnd::OnLButtonUp(nFlags, point);
}
class MyApp: public CWinApp
{
MFC_Tutorial_Window *wnd;
public:
BOOL InitInstance()
{
wnd = new MFC_Tutorial_Window();
m_pMainWnd = wnd;
m_pMainWnd->ShowWindow(1);
return 1;
}
};
MyApp theApp;