打开VC6.0,使用MFC AppWizard[exe]新建一个单文档的应用程序。
1)新建一个绘图菜单。打开ResourceView选项卡--》Menu/IDR_MAINFRAME-->双击菜单栏上的空白处,添加如下内容:
图(1)具有弹出项的菜单
图(2)菜单项“点”
还有两个菜单项:ID: IDM_RECTANGLE ,Caption:矩形
IDM_ELLIPSE ,Caption: 椭圆
2)在View类中,为“点、直线、矩形、椭圆”分别添加四个响应函数:OnDot、OnLine、OnRectangle、OnEllipse。
以OnDot为例,步骤是,右击“点”菜单--》Class Wizard-->Class name选择“CXXXView”, Object选择“IDM_DOT”,Message选择“COMMMAD”-->选择Add Function-->Edit Code:如下:
图(3)为IDM_DOT添加信息响应函数
3)选择视图类CXXXView.h,添加两个成员变量:
public UINT m_nDrawType; //绘制类型;
public CPoint m_ptOrigin; //起点;
例如,“public UINT m_nDrawType;”,右击“CXXXView”--》Add member Variable-->如下:
图(4)添加成员变量“public UINT m_nDrawType;”
4)在构造函数CXXXVIEW()中,对两个成员变量进行初始化。
CGraphicView::CGraphicView()
{
// TODO: add construction code here
m_nDrawType=0;
m_ptOrigin=0;
}
void CGraphicView::OnDot()
{
// TODO: Add your command handler code here
m_nDrawType=1;
}
void CGraphicView::OnLine()
{
// TODO: Add your command handler code here
m_nDrawType=2;
}
void CGraphicView::OnRectangle()
{
// TODO: Add your command handler code here
m_nDrawType=3;
}
void CGraphicView::OnEllipse()
{
// TODO: Add your command handler code here
m_nDrawType=4;
}
4) 选择视图类CXXXView.h,添加两个按钮响应事件:OnLButtonDown()和OnLButtonUp()。
并操作画图:画点、画直线、画矩形、画椭圆。
void CGraphicView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
m_ptOrigin=point;
CView::OnLButtonDown(nFlags, point);
}
void CGraphicView::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CClientDC dc(this);
CBrush *pBrush = CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH));
dc.SelectObject(pBrush);
switch(m_nDrawType){
case 1:
dc.SetPixel(point,RGB(0,0,0));
break;
case 2:
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
break;
case 3:
dc.Rectangle(CRect(m_ptOrigin,point));
break;
case 4:
dc.Ellipse(CRect(m_ptOrigin,point));
break;
}
CView::OnLButtonUp(nFlags, point);
}
效果如下: