VC MFC编程实例
- 格式:ppt
- 大小:203.00 KB
- 文档页数:13
VS2008下计算器的MFC编程实现简单的计算器编程,完全在VS2008下实现,主要用于熟悉VS2008的功能。
谨以此分享给和我一样初学MFC的朋友们。
STEP1:页面设计1.新建工程首先打开Visual Studio2008,选择MFC应用程序,设定好路径和工程名(这里我设置工程名为为“Calculator”)。
这里要注意的是在创建向导步骤1的时候,我们选择“基本对话框”,其他选项默认即可。
之后我们可以点击完成便看到以下界面:此时我们把当前页面上原配的控件按Delete全部清除(如下图)2.添加控件接着我们按照MFC自带的控件选项进行我们本次计算器的控件添加。
点击右侧的工具栏按钮(以下是控件)我们在原先清空的界面中依次用上图控件画出一个基本的计算器页面(如下图)。
影响用户的心情。
3.修改空间ID和Caption上图各控件类型如下:Edit ControlButtonGroup Box:选择其中一个GroupBox,右键单击,选择[属性]。
在右边显示属性对话框。
每个控件“属性”都有属于它自己的ID,默认的Group Box的ID为IDC_STATIC,而且Cap当然我们为了“顾名思义”,对控件ID进行修改成我们容易辨认的(也可以不改),添加完控件并修改ID。
4个Group Box的ID分别修改为IDC_STATIC_FRAME ,IDC_STATIC_IN, IDC_STATIC_RESULT, IDC_STATIC_BUTTON 控件Edit Control和Button也按相同的办法处理。
ID设置完成可以在“Resourse.h”中查看。
完成修改ID后,就需给控件添加消息响应了。
在属性对话框的上方点击闪电“”图标,添加控件事件。
如对于按钮“”,点击“”点击下拉键头,添加控件事件,页面自动切换到代码的编辑页面,如“添加OnBnClickedButton5”MFC默认下了的响应信息都为On_开头。
int Str2Hex(CString str, UINT32* data)实现的功能是将str(16进制)->数字。
比如11转换成17。
21转换成33。
Visual C++通用范例开发金典\Visual C++通用范例开发金典ch011. IDC_STATIC1:void CCStatic2Dlg::OnStatic1(){// TODO: Add your control notification handler code hereCString str;GetDlgItem(IDC_STATIC1)->GetWindowText(str);if("Hello,World!"==str){GetDlgItem(IDC_STATIC1)->SetWindowText("Visual C++!");}if("Visual C++!"==str){GetDlgItem(IDC_STATIC1)->SetWindowText("I like C++");}if("I like C++"==str){GetDlgItem(IDC_STATIC1)->SetWindowText("Hello,World!");}}2.BOOL CRadio_Button1Dlg::OnInitDialog()中的代码:CheckRadioButton(IDC_RADIO1,IDC_RADIO3,IDC_RADIO1);3.BOOL CButton3Dlg::OnInitDialog()中的代码:CheckRadioButton(IDC_RADIO1,IDC_RADIO3,IDC_RADIO3);CButton *ptn=(CButton *)GetDlgItem(IDC_CHECK1);ptn->SetCheck(1);在void CButton3Dlg::OnOK(){// TODO: Add extra validation hereCString str,strCtrl;int i;str="您的年级:";UINT nID1=GetCheckedRadioButton(IDC_RADIO1,IDC_RADIO3);GetDlgItemText(nID1,strCtrl);str=str+strCtrl;str=str+"\n你最喜欢的课程:";UINT nID2[4]={IDC_CHECK1,IDC_CHECK2,IDC_CHECK3,IDC_CHECK4};CButton *ptn;for(i=0;i<4;i++){ptn=(CButton *)GetDlgItem(nID2[i]);if(1==ptn->GetCheck()){ptn->GetWindowText(strCtrl);str=str+strCtrl;str=str+" ";}}MessageBox(str);// CDialog::OnOK();}4.void CCstatic1Dlg::OnOK(){if (static1.m_hWnd){static1.DestroyWindow();}else{static1.Create("生成的新的静态文本框",WS_CHILD|WS_VISIBLE,CRect(0,0,200,30),this,11);}// CDialog::OnOK();}5.void CCShrinkView::OnShrink(){// TODO: Add your command handler code hereCShrink_Dlg* pt1=new CShrink_Dlg;pt1->DoModal();}void CShrink_Dlg::OnButton1(){// TODO: Add your control notification handler code hereCString str;GetDlgItemText(IDC_BUTTON1,str);if("收缩<<"==str)SetDlgItemText(IDC_BUTTON1,"扩展>>");elseSetDlgItemText(IDC_BUTTON1,"收缩<<");static CRect rectLarge;static CRect rectSmall;if(rectLarge.IsRectNull()){CRect temp;GetWindowRect(&rectLarge);GetDlgItem(IDC_SHRINK)->GetWindowRect(&temp);rectSmall.left=rectLarge.left;rectSmall.top=rectLarge.top;rectSmall.right=rectLarge.right;rectSmall.bottom=temp.top;}if(str=="收缩<<"){SetWindowPos(NULL,0,0,rectSmall.Width(),rectSmall.Height(),SWP_NOMOVE|SWP_NO ZORDER);}else{SetWindowPos(NULL,0,0,rectLarge.Width(),rectLarge.Height(),SWP_NOMOVE|SWP_NO ZORDER);}}6.BOOL CCEdit_6Dlg::OnInitDialog()中的:CTime time;time=CTime::GetCurrentTime();m_time=time.Format("%x--%X");UpdateData(FALSE);void CCEdit_6Dlg::OnTimer(UINT nIDEvent){CTime time;time=CTime::GetCurrentTime();m_time=time.Format("%Y-%m-%d %H:%M:%S");UpdateData(FALSE);CDialog::OnTimer(nIDEvent);}7.只有一个例子,其它的仿照void CCEdit4Dlg::OnGreenRadio3(){colour = RGB(0,255,0);m_edit.SetFocus();}8.class CColorEdit : public CEdit自己新创了一个类HBRUSH CColorEdit::CtlColor(CDC* pDC, UINT nCtlColor){// TODO: Change any attributes of the DC hereCDC* dc = GetDC(); //获取画布对象CRect rect;GetClientRect(rect); //获取客户区域rect.InflateRect(3,3,3,3);//将客户区域增大3个像素CBrush brush (m_color);//创建画刷dc->FrameRect(rect,&brush);//绘制边框// TODO: Return a non-NULL brush if the parent's handler should not be called return NULL;}void CColorEdit::SetColorEdit(COLORREF color){m_color=color;}//m_color是CColorEdit的一个成员函数BOOL CCEdit_5Dlg::OnInitDialog()中的m_edit1.SetColorEdit(RGB(255,0,0));m_edit2.SetColorEdit(RGB(0,0,255));9.void CCEdit_1Dlg::OnButton1(){// TODO: Add your control notification handler code hereCString str;UpdateData(TRUE);if((strcmp(m_name,"张三")==0)&&(strcmp(m_password,"1113")==0)) str="密码正确,登陆成功!";else if((strcmp(m_name,"")==0)||(strcmp(m_password,"")==0)) str="请输入用户名或密码:";elsestr="用户名或密码错误:";MessageBox(str);}10.void CCEdit_2Dlg::OnChangeEdit1(){UpdateData(TRUE);// m_write="d\nyyy";m_read=m_write;UpdateData(FALSE);}11.CSpinButtonCtrl m_spinage;BOOL CSpinButtonDlg::OnInitDialog()中的:m_spinage.SetRange(1,100);m_spinage.SetBase( 0 );void CSpinButtonDlg::OnDeltaposSpin1(NMHDR* pNMHDR, LRESULT* pResult) {NM_UPDOWN* pNMUpDown = (NM_UPDOWN*)pNMHDR;// TODO: Add your control notification handler code hereUpdateData(TRUE);m_age=m_age+(float)pNMUpDown->iDelta;if(m_age<0) m_age=0;if(m_age>10) m_age=10;UpdateData(FALSE);*pResult = 0;}void CSpinButtonDlg::OnOK(){// TODO: Add extra validation hereUpdateData(TRUE);CString str;char *temp=new char;itoa(m_age,temp,10);str="结果显示:\n姓名:";str+=m_name;str+="\n年龄:";str+=temp;str+="\n年级:";str+=m_class;str+="\n电话:";str+=m_phone;MessageBox(str);//CDialog::OnOK(); }。
VC(MFC)开发OPENGL程序作者:李英江日期: 2006-08-10 19:07:00网站:转载请保留作者内容!利用使用VC开发OPENGL程序,运用MFC库,做一个简单例子我简单介绍一下图形接口,现在流行的两大图形接口Direct3D 和OpenGL,Direct3D主要是针对游戏,像starcaft星际争霸,它支持DX5.0以上的版本,但是不少游戏同时支持两种图形加速,如CS,魔兽争霸。
OpenGL主要是针对专业的图形应用,在军事,医学,GIS地理信息系统,动画(3dsmax,maya...),电影,等应用广泛,并且可以在不同的平台上应用,DX相对来说就只能限于Windows操作系统了。
1.运用MFC向导,生成一个单文档应用程序,不做任何事的MFC 框架程序。
2.视图类中添加窗口样式。
/************************************************************** *******/BOOL CMfc_basicView::PreCreateWindow(CREATESTRUCT& cs){// Add Window styles required for OpenGL before window iscreatedcs.style |= (WS_CLIPCHILDREN | WS_CLIPSIBLINGS | CS_OWNDC);return CView::PreCreateWindow(cs);}/************************************************************** *******/3.在afxcmn.h中包含OPENGL头文件。
/************************************************************** *******/#include <afxcmn.h>// MFC support for Windows Common Controls// Inserted these files for openGL#include <gl.h>#include <glut.h>#include <glu.h>#include <glaux.h>#endif // _AFX_NO_AFXCMN_SUPPORT/************************************************************** *******/4.视图类中 .h文件中加入四个public 成员变量/************************************************************** *******/HGLRC m_hRC; // Permanent Rendering ContextHDC m_myhDC; // Private GDI Device Contextint m_height; // Stores the height of the Viewint m_width; // Stores the width of the view/************************************************************** *******/5.视图类中右键添加一个BOOL成员函数SetupPixelFormat/************************************************************** *******/BOOL COglm_demoView::SetupPixelFormat(){GLuint PixelFormat;static PIXELFORMATDESCRIPTOR pfd= {sizeof(PIXELFORMATDESCRIPTOR),// Size Of This Pixel Format Descriptor1,// Version Number (?)PFD_DRAW_TO_WINDOW | // Format Must Support WindowPFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format24, // Select A 24Bit Color Depth0, 0, 0, 0, 0, 0, // Color Bits Ignored (?)0, // No Alpha Buffer0, // Shift Bit Ignored (?)0, // No Accumulation Buffer0, 0, 0, 0, // Accumulation Bits Ignored (?)16, // 16Bit Z-Buffer (Depth Buffer)0, // No Stencil Buffer0, // No Auxiliary Buffer (?)PFD_MAIN_PLANE, // Main Drawing Layer0, // Reserved (?)0, 0, 0 // Layer Masks Ignored (?)};m_myhDC = ::GetDC(m_hWnd); // Gets A Device Context For The WindowPixelFormat = ChoosePixelFormat(m_myhDC, &pfd); // Finds The Closest Match To The Pixel Format We Set Aboveif (!PixelFormat){::MessageBox(0,"Can't Find A Suitable PixelFormat.","Error",MB_OK|MB_ICONERROR);PostQuitMessage(0);// This Sends A 'Message' Telling The Program To Quitreturn false ; // Prevents The Rest Of The Code From Running}if(!SetPixelFormat(m_myhDC,PixelFormat,&pfd)){::MessageBox(0,"Can't Set The PixelFormat.","Error",MB_OK|MB_ICONERROR);PostQuitMessage(0);return false;}m_hRC = wglCreateContext(m_myhDC);if(!m_hRC){::MessageBox(0,"Can't Create A GL Rendering Context.","Error",MB_OK|MB_ICONERROR);PostQuitMessage(0);return false;}if(!wglMakeCurrent(m_myhDC, m_hRC)){::MessageBox(0,"Can't activate GLRC.","Error",MB_OK|MB_ICONERROR);PostQuitMessage(0);return false;}// Now that the screen is setup we can// initialize OpenGL();InitGL();return true;}/************************************************************** *******/6.关闭WM_ERASEBACKGROUND消息,不关闭的话,画图时会闪动.在视图类中选择“Add Windows Message Handler”加入消息处理函数./************************************************************** *******/BOOL CMfc_basicView::OnEraseBkgnd(CDC* pDC){return FALSE;}/************************************************************** *******/7.初始化OPENGL 添加InitGL()函数./************************************************************** *******/void CMfc_basicView::InitGL(){// Enables Depth TestingglEnable(GL_DEPTH_TEST);// Enable the point size for selected pointsglPointSize(5.0f);// This Will Clear The Background Color To BlackglClearColor(.4, 0.2, 0.0, 0.0f);// Reset the current projection matrixSetProjection();glMatrixMode(GL_MODELVIEW);glLoadIdentity();//Enable back face culling, defaults to Clock wise vertices.glEnable(GL_CULL_FACE);glEnable(GL_COLOR_MATERIAL);glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);glShadeModel(GL_SMOOTH);glPolygonMode(GL_FRONT, GL_FILL);}/************************************************************** *******/8. 在视图类中添加调窗口大小的处理函数OnSize() 消息句柄/************************************************************** *******/void CMfc_basicView::OnSize(UINT nType, int cx, int cy){CView::OnSize(nType, cx, cy);glMatrixMode(GL_MODELVIEW);glLoadIdentity();// Make the rendering context currentwglMakeCurrent(m_myhDC,m_hRC);// Reset The Current Viewport And Perspective TransformationglViewport(0, 0, cx, cy);m_height= cy;m_width = cx;// Calculate The Aspect Ratio Of The WindowgluPerspective(60.0f,(GLfloat)cx/(GLfloat)cy,0.1f,1000.0f);}9.添加SetPorjection()函数void CMfc_basicView::SetProjection(){glViewport(0, 0, m_width, m_height);// Reset The Projection MatrixglMatrixMode(GL_PROJECTION);glLoadIdentity();// It's a perspective projection// Calculate The Aspect Ratio Of The WindowgluPerspective(60.0f,(GLfloat)m_width/(GLfloat)m_height, 0.1f,3000.0f);}/************************************************************** *******/10.在Project 菜单选择Settings. 单击Link 选项页Object/library Module添加库文件.opengl32.lib glu32.lib glut.lib glaux.lib11.在视图类中加入OnCreate消息句柄/*********************************************************************/int CMfc_basicView::OnCreate(LPCREATESTRUCT lpCreateStruct){if (CView::OnCreate(lpCreateStruct) == -1)return -1;SetupPixelFormat();wglMakeCurrent(NULL,NULL);return 0;}/************************************************************** *******///现在编译程序的话,会看到一个无法刷新的应用程序了。
一、实验目的(1) 熟悉开发环境;(2) 掌握应用MFC类库编写鼠标绘图程序的方法;(3) 掌握MFC环境中绘图函数的使用方法。
二、实验内容创建一个单文档应用程序,实现鼠标的绘图功能。
要求:(1) 创建一个工具栏,有线段、矩形、椭圆三个按钮;(2) 绘图前,选择工具栏上的按钮,确定图形的形状。
按下鼠标左键,开始绘图,结合鼠标的光标坐标值,来确定图形的形状和大小,并随着鼠标的移动在屏幕上实时绘制图形,放开鼠标左键,确定最后的图形,绘制在屏幕上。
三、实验处理列表实现绘图功能的代码清单:1、代码如下#if !defined(AFX_PIC_H__00F5F2B9_A2A6_4ED6_907E_EC07AA16 8545__INCLUDED_)#defineAFX_PIC_H__00F5F2B9_A2A6_4ED6_907E_EC07AA168545__INCL UDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000class CPic{public:CPic();virtual ~CPic();void Draw(CDC *PDC);public:UINT m_nDrawType;int m_nX0;int m_nY0;int m_nX1;int m_nY1;};#endif// !defined(AFX_PIC_H__00F5F2B9_A2A6_4ED6_907E_EC07AA1685 45__INCLUDED_)2、代码如下:// Pic.cpp: implementation of the CPic class.////////////////////////////////////////////////////////////////////////#include ""#include "Shiyan8.h"#include ""#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE[]=__FILE__;#define new DEBUG_NEW#endif//////////////////////////////////////////////////////////////////////// Construction/Destruction//////////////////////////////////////////////////////////////////////CPic::CPic(){}CPic::~CPic(){}void CPic::Draw(CDC *pDC){CPen PenLN,*pOldPen;(PS_SOLID,3,RGB(255,0,0));pOldPen = pDC->SelectObject(&PenLN);switch(m_nDrawType){case 0:pDC->MoveTo(m_nX0,m_nY0);pDC->LineTo(m_nX1,m_nY1);break;case 1:pDC->Ellipse(m_nX0,m_nY0,m_nX1,m_nY1);break;case 2:pDC->Rectangle(m_nX0,m_nY0,m_nX1,m_nY1);break;}pDC->SelectObject(pOldPen);}3、程序如下:// Shiyan8View.cpp : implementation of the CShiyan8View class//#include ""#include "Shiyan8.h"#include "Shiyan8Doc.h"#include "Shiyan8View.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif/////////////////////////////////////////////////////////////////////////////// CShiyan8ViewIMPLEMENT_DYNCREATE(CShiyan8View, CView)BEGIN_MESSAGE_MAP(CShiyan8View, CView)//{{AFX_MSG_MAP(CShiyan8View)ON_COMMAND(ID_DRAW_FILEOPEN, OnDrawFileopen)ON_UPDATE_COMMAND_UI(ID_DRAW_FILEOPEN, OnUpdateDrawFileopen)ON_COMMAND(ID_DRAW_FILESA VE, OnDrawFilesave)ON_UPDATE_COMMAND_UI(ID_DRAW_FILESA VE, OnUpdateDrawFilesave)ON_WM_LBUTTONDOWN()ON_WM_MOUSEMOVE()ON_WM_LBUTTONUP()//}}AFX_MSG_MAPON_COMMAND_RANGE(ID_DRAWTYPE_LINE,ID_DRAWTYPE_RECT,OnDrawType)ON_UPDATE_COMMAND_UI_RANGE(ID_DRAWTYPE_LIN E, ID_DRAWTYPE_RECT,OnUpdateDrawType)// Standard printing commandsON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)ON_COMMAND(ID_FILE_PRINT_DIRECT,CView::OnFilePrint)ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)END_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CShiyan8View construction/destructionCShiyan8View::CShiyan8View(){// TODO: add construction code herem_nDrawType = 0;m_nX0 = 0;m_nY0 = 0;m_nX1 = 0;m_nY1 = 0;m_nPicNum = 0;}CShiyan8View::~CShiyan8View(){}BOOL CShiyan8View::PreCreateWindow(CREATESTRUCT& cs) {// TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT csreturn CView::PreCreateWindow(cs);}/////////////////////////////////////////////////////////////////////////////// CShiyan8View drawingvoid CShiyan8View::OnDraw(CDC* pDC){CShiyan8Doc* pDoc = GetDocument();ASSERT_V ALID(pDoc);// TODO: add draw code for native data herefor(int i=0;i<m_nPicNum;i++){m_Pic[i].Draw(pDC);}}/////////////////////////////////////////////////////////////////////////////// CShiyan8View printingBOOL CShiyan8View::OnPreparePrinting(CPrintInfo* pInfo){// default preparationreturn DoPreparePrinting(pInfo);}void CShiyan8View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/){// TODO: add extra initialization before printing}void CShiyan8View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/){// TODO: add cleanup after printing}/////////////////////////////////////////////////////////////////////////////// CShiyan8View diagnostics#ifdef _DEBUGvoid CShiyan8View::AssertValid() constCView::AssertValid();}void CShiyan8View::Dump(CDumpContext& dc) const{CView::Dump(dc);}CShiyan8Doc* CShiyan8View::GetDocument() // non-debug version is inline{ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CShiyan8Doc)));return (CShiyan8Doc*)m_pDocument;}#endif //_DEBUG/////////////////////////////////////////////////////////////////////////////// CShiyan8View message handlersvoid CShiyan8View::OnDrawFileopen(){// TODO: Add your command handler code here}void CShiyan8View::OnUpdateDrawFileopen(CCmdUI* pCmdUI){// TODO: Add your command update UI handler code herepCmdUI->Enable(FALSE);}void CShiyan8View::OnDrawFilesave(){// TODO: Add your command handler code herevoid CShiyan8View::OnUpdateDrawFilesave(CCmdUI* pCmdUI){// TODO: Add your command update UI handler code herepCmdUI->Enable(FALSE);}void CShiyan8View::OnDrawType(WORD nID){m_nDrawType = nID-ID_DRAWTYPE_LINE;}void CShiyan8View::OnUpdateDrawType(CCmdUI* pCmdUI){pCmdUI->SetRadio(m_nDrawType == pCmdUI->m_nID-ID_DRAWTYPE_LINE);}void CShiyan8View::OnLButtonDown(UINT nFlags, CPoint point){// TODO: Add your message handler code here and/or call defaultm_nX0 = m_nX1 = ;m_nY0 = m_nY1 = ;CView::OnLButtonDown(nFlags, point);}void CShiyan8View::OnMouseMove(UINT nFlags, CPoint point){// TODO: Add your message handler code here and/or call defaultCClientDC dc(this);CPen PenBK,PenLN,*pOldPen;if(nFlags & MK_LBUTTON)(PS_SOLID,1,RGB(255,255,255)); (PS_DASH, 1,RGB(255,0,0)); pOldPen = (&PenBK);switch(m_nDrawType){case 0:(m_nX0,m_nY0);(m_nX1,m_nY1);break;case 1:(m_nX0,m_nY0,m_nX1,m_nY1);break;case 2:(m_nX0,m_nY0,m_nX1,m_nY1);break;}(&PenLN);m_nX1 = ;m_nY1 = ;switch(m_nDrawType){case 0:(m_nX0,m_nY0);(m_nX1,m_nY1);break;case 1:(m_nX0,m_nY0,m_nX1,m_nY1);break;case 2:(m_nX0,m_nY0,m_nX1,m_nY1);break;}(pOldPen);CView::OnMouseMove(nFlags, point);}void CShiyan8View::OnLButtonUp(UINT nFlags, CPoint point){// TODO: Add your message handler code here and/or call default CClientDC dc(this);CPen PenBK,PenLN,*pOldPen;(PS_SOLID,1,RGB(255,255,255));(PS_SOLID,3,RGB(255,0,0));pOldPen = (&PenBK);switch(m_nDrawType){case 0:(m_nX0,m_nY0);(m_nX1,m_nY1);break;case 1:(m_nX0,m_nY0,m_nX1,m_nY1);break;case 2:(m_nX0,m_nY0,m_nX1,m_nY1);break;}(&PenLN);m_nX1 = ;m_nY1 = ;switch(m_nDrawType){case 0:(m_nX0,m_nY0);(m_nX1,m_nY1);break;case 1:(m_nX0,m_nY0,m_nX1,m_nY1);break;case 2:(m_nX0,m_nY0,m_nX1,m_nY1);break;}m_Pic[m_nPicNum].m_nDrawType = m_nDrawType;m_Pic[m_nPicNum].m_nX0 = m_nX0;m_Pic[m_nPicNum].m_nY0 = m_nY0;m_Pic[m_nPicNum].m_nX1 = m_nX1;m_Pic[m_nPicNum].m_nY1 = m_nY1;m_nPicNum++;(pOldPen);CView::OnLButtonUp(nFlags, point);}其他的程序略四、实验总结:1.在Resource View中展开menu资源菜单中,设计如下:2、在Resource View中展开Toorlbar资源菜单中,设计如下:3、本实验的一部分代码可以从实验六中复制过来,但应注意变量名称。
实验四 MFC图形绘制编程实验一、实验目的(1) 熟悉Visual C++ 6.0开发环境;(2) 掌握MFC消息映射的操作步骤;(2) 掌握MFC图形输出的方法;(3) 理解设备环境、画笔、画刷的概念,掌握常用的绘图函数。
二、实验内容请编写程序,要求如下:(1) 定义一支黄色画笔,绘制一条线段;(1) 定义一支紫色画笔,绘制一条多段线;(3) 定义一支红色画笔,绘制一个正方形,并用适当的画刷填充图形内部;(4) 定义一支绿色画笔,绘制一个圆,并用适当的画刷填充图形内部;(5) 定义一支蓝色画笔,绘制一个正六边形,并用适当的画刷填充图形内部。
三、实验报告1.列出图形绘制程序代码清单:(1)在头文件Demo.h中:#include "afxwin.h"class CDemoWnd:public CFrameWnd{public:CDemoWnd();~CDemoWnd();public:LRESULT OnPaint(WPARAM wParam,LPARAM lParam);DECLARE_MESSAGE_MAP()public:int m_nX0;int m_nY0;int m_nX1;int m_nY1;};class CDemoApp:public CWinApp{public:BOOL InitInstance();};CDemoApp ThisApp;(2)在源文件Demo.cpp中:#include "Demo.h"CDemoWnd::CDemoWnd(){m_nX0 = 0;m_nY0 = 0;m_nX1 = 0;m_nY1 = 0;}CDemoWnd::~CDemoWnd(){}BEGIN_MESSAGE_MAP(CDemoWnd,CFrameWnd)ON_MESSAGE(WM_PAINT,OnPaint)END_MESSAGE_MAP()LRESULT CDemoWnd::OnPaint(WPARAM wParam,LPARAM lParam) {CPaintDC dc(this);CPen Pen1,*pOldPen1;Pen1.CreatePen(PS_SOLID,10,RGB(255,255,0));pOldPen1=dc.SelectObject(&Pen1);dc.SelectObject(&Pen1);dc.MoveTo(10,10);dc.LineTo(100,100);CPen Pen2,*pOldPen2;Pen2.CreatePen(PS_SOLID,4,RGB(255,0,255));pOldPen2=dc.SelectObject(&Pen2);dc.SelectObject(&Pen2);POINT pt1[]={{100,10},{10,180},{200,150}};dc.Polyline(pt1,3);CPen Pen3,*pOldPen3;dc.SelectStockObject(BLACK_BRUSH);Pen3.CreatePen(PS_SOLID,4,RGB(255,0,0));pOldPen3=dc.SelectObject(&Pen3);dc.SelectObject(&Pen3);dc.Rectangle(300,50,400,150);CPen Pen4,*pOldPen4;dc.SelectStockObject(GRAY_BRUSH);Pen4.CreatePen(PS_SOLID,4,RGB(0,255,0));pOldPen4=dc.SelectObject(&Pen4);dc.SelectObject(&Pen4);dc.Ellipse(500,200,700,400);CPen Pen5,*pOldPen5;Pen5.CreatePen(PS_SOLID,4,RGB(0,0,255));pOldPen5=dc.SelectObject(&Pen5);dc.SelectStockObject(DKGRAY_BRUSH);dc.SelectObject(&Pen5);POINT pt2[]={{250,250},{400,250},{475,379},{400,509},{250,509},{175,379}};dc.Polygon(pt2,6);return 0;}BOOL CDemoApp::InitInstance(){CDemoWnd *pMainWnd = new CDemoWnd();pMainWnd->Create(NULL,"Demo Mini-MFC");pMainWnd->ShowWindow(m_nCmdShow);pMainWnd->UpdateWindow();m_pMainWnd = pMainWnd;return TRUE;}2、程序运行结果:3、总结在MFC 程序中绘制图形的基本操作步骤:(1)获取图形设备接口。
#include <windows.h>#include <time.h>#include <stdlib.h>#include <stdio.h>#define tDown 1 //方块下落定时器的标识(编号)#define tPaint 2 //重绘定时器的标识(编号)#define tDownTime 500 //方块下落一行位置的时间间隔#define tPaintTime 50 //窗口重绘的时间间隔#define ROW 24 //地图的行数目(第23行不用)#define COL 14 //地图的列数目(第0列和第13列不用)#define MAX_CLASS 7 //方块形状数目#define LEN 20 //每个方格大小为20×20像素#define StartY -1 * LEN + 5 //-15,绘制俄罗斯方块地图时的边界起始位置#define StartX -1 * LEN + 5 //-15int iDeleteRows = 0; //总共清除的行int iTotalNum = 0; //总得分char WindowTxt[100] = "俄罗斯方块游戏自动求解已关闭"; //窗口标题char s1[] = "关闭", s2[] = "启动"; //用于启动/关闭自动求解功能时显示不同的标题bool bAuto; //是否自动求解的标志bool Pause; //是否暂停的标志int Map[ROW][COL]; //俄罗斯方块的地图(被占据的方格为1,否则为0) int CurrentBox[4][4]; //当前落下的方块int CurrentY, CurrentX; //当前落下方块的当前位置(指左上角位置)int NextBox[4][4]; //下一个将落下的方块int Box[MAX_CLASS][4][4] = //7种方块形状{{{0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0}},{{0,0,0,0},{0,1,0,0},{1,1,1,0},{0,0,0,0}},{{0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0}},{{0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0}},{{0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0}},{{0,1,1,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}{{0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0}}};void InitMap( ); //初始化地图int NewFall( ); //新的方块落下void BuildNextBox( ); //产生下一个随机的方块int Test( int y, int x, int box[4][4] ); //测试在(y,x)位置是否能放置方块box,能放置返回1,否则返回0int Drop( ); //定时时间到,当前方块下降一行位置void PutBox( ); //放置当前方块int Move( int Right ); //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动void Clear( ); //清除满足条件的行int Rotate( ); //测试旋转是否可行,如果可行则旋转当前方块int RotateTest( int Box1[4][4], int Box2[4][4] ); //旋转当前方块int count1( int y, int x, int box[4][4] ); //新增函数int BestStartX( ); //新增函数LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); //窗口处理函数声明int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow ) //入口函数{static TCHAR szAppName[ ] = TEXT ("Russion");HWND hwnd;MSG msg;WNDCLASS wndclass;wndclass.style = CS_HREDRAW | CS_VREDRAW;wndclass.lpfnWndProc = WndProc;wndclass.cbClsExtra = 0;wndclass.cbWndExtra = 0;wndclass.hInstance = hInstance;wndclass.hIcon = LoadIcon( NULL, IDI_APPLICATION );wndclass.hCursor = LoadCursor( NULL, IDC_ARROW );wndclass.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );wndclass.lpszMenuName = NULL;wndclass.lpszClassName = szAppName;if( !RegisterClass( &wndclass ) ){MessageBox( NULL, TEXT ("Program requires Windows NT!" ),szAppName, MB_ICONERROR );return 0;}hwnd = CreateWindow( szAppName, WindowTxt,WS_OVERLAPPED | WS_SYSMENU | WS_BORDER,CW_USEDEFAULT, CW_USEDEFAULT,(COL + 4) * LEN, //窗口宽度:(14+4)×20=360像素ROW * LEN, //窗口高度:24×20=480像素(包括标题栏部分)NULL, NULL, hInstance, NULL );ShowWindow( hwnd, iCmdShow );UpdateWindow( hwnd );while( GetMessage( &msg, NULL, 0, 0 ) ){TranslateMessage( &msg );DispatchMessage( &msg );}return msg.wParam;}//初始化地图(将第0列和第13列、第23行设置为1(被占据),其他位置设置为0) void InitMap( ){int y, x;for( y = 0; y < ROW; y++ ){for( x = 0; x < COL; x++ ){//第0列、第13列、第23行设置为1(被占据)if( x < 1 || x > COL - 2 || y > ROW - 2 )Map[y][x] = 1;else Map[y][x] = 0;}}}//计算在(y,x)位置(左上角位置)上放置方块box后空出的方格数int count1( int y, int x, int box[4][4] ){if( !Test(y,x,box) ) return 100; //不能在(y,x)位置放置box,返回∞if( Test(y+1,x,box) ) return 100; //如果box还能下降,也返回∞int tmpy, tmpx;int c = 0; //空出的方格数for( tmpx = 0; tmpx < 4; tmpx++ ) //考虑第0~3列{for( tmpy = 3; tmpy >= 0; tmpy-- ){if( box[tmpy][tmpx] ) break;}tmpy++;if( tmpy>0 ){for( ; tmpy<4; tmpy++ ){if( tmpy+y<0 || tmpy+y>=ROW || tmpx+x<0 || tmpx+x>=COL ) continue;if(!Map[tmpy+y][tmpx+x]) c++; //空出的方格}}}return c;}//当启动自动求解功能时,求下一个方块的最佳下降位置//策略1为:放置后,空出的方格数最少,为MinC1,此时能达到最高位置为MaxY1,该位置为BestX1;//策略2为:放置后,能下降的位置最高,为MaxY2,此时空出的方格数为MinC2,该位置为BestX2;//必有MaxY1<=MaxY2, MinC1>=MinC2//取二者的折衷,策略为:优先采取策略1,但如果MinC2==MinC1或MaxY2>=MaxY1+2,则取策略2int BestStartX( ){int X, Y, tmpx, tmpy; //循环变量int BestX = 0, MaxY = 0, MinC = 100;//最终所求的最佳下降位置int BestX1, MaxY1, MinC1; //策略1:MinC:最佳位置处放置方块时,空出的空格最少,BestX:最佳下降位置,MaxY:能下降到的位置int BestX2, MaxY2, MinC2; //策略2:最佳位置为能下降的位置最高int c; //以上策略求最值时用到的辅助变量int tBox1[4][4], tBox2[4][4]; //tBox2为实现旋转时用到的临时变量int Rotates = 0, Rotates1 = 0, Rotates2 = 0;//找到最佳位置后,当前方块需要旋转的次数int Last1, Last2; //Last1为下一个方块未旋转时最下一个方格所在的行,Last2为旋转后最下一个方格所在的行memcpy(tBox1, NextBox, sizeof(tBox1)); memcpy(tBox2, NextBox, sizeof(tBox1)); for( tmpy=3; tmpy>=0; tmpy-- ) //统计tBox1中最下一个方格所在的行{for( tmpx=0; tmpx<4; tmpx++ ) if(tBox1[tmpy][tmpx]) break;if(tmpx<4) break;}Last1 = tmpy;BestX1 = 0, MaxY1 = 0, MinC1 = 100; BestX2 = 0, MaxY2 = 0, MinC2 = 100;//枚举从第0~COL-4列下落for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last1>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last1;if( Y+Last1>MaxY2 || Y+Last1==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last1;}//第1次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 1;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 1;}//第2次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 2;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 2;}//第3次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 3;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 3;}MinC = MinC1, BestX = BestX1, MaxY = MaxY1, Rotates = Rotates1;if( MinC2==MinC1 || MaxY2>=MaxY1+2 )MinC = MinC2, BestX = BestX2, MaxY = MaxY2, Rotates = Rotates2;if( Rotates>0 ){for( int i=0; i<Rotates; i++ ){RotateTest(NextBox, tBox1);memcpy(NextBox, tBox1, sizeof(tBox1));}}return BestX;}int NewFall( ) //新的方块落下(如果能落下返回1,否则不能落下返回0(程序就该结束了)) {int y, x;CurrentY = 0; //当前方块的当前位置是指该方块(4×4大小)的左上角所在位置if(bAuto) CurrentX = BestStartX( );else CurrentX = COL / 2 - 2; //初始为(0,5)for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = NextBox[y][x];}BuildNextBox( ); //产生下一个随机的方块return Test( CurrentY, CurrentX, CurrentBox );}int no[400] = {3,3,5,1};void BuildNextBox( ) //产生下一个随机的方块{static int j=0;int i, y, x;i = rand()%MAX_CLASS; //随机生成0~6的整数for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )NextBox[y][x] = Box[i][y][x];}}//测试在(y,x)位置(左上角位置)是否能放置方块box,能放置返回1,否则返回0int Test( int y, int x, int box[4][4] ){int tmpy, tmpx;for( tmpy = 0; tmpy < 4; tmpy++ ){for( tmpx = 0; tmpx < 4; tmpx++ ){if( Map[tmpy + y][tmpx + x] && box[tmpy][tmpx] )return 0;}}return 1;}int Drop( ) //定时时间到,当前方块下降一行位置(如果能下降返回1,否则返回0){int NewY;NewY = CurrentY + 1;if( Test( NewY, CurrentX, CurrentBox ) ){CurrentY = NewY;return 1;}return 0;}void PutBox( ) //在当前位置(CurrentY,CurrentX)放置当前方块(此时当前方块已经不能下降了){int y, x;for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] )Map[CurrentY + y][CurrentX + x] = CurrentBox[y][x];}}}int Move( int Right ) //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动{int x;if( Right ) x = CurrentX + 1; //向右移动一列位置else x = CurrentX - 1; //向左移动一列位置if( Test( CurrentY, x, CurrentBox ) ){CurrentX = x;return 1;}return 0;}void Clear( ) //清除满足条件的行{int y, x; //循环变量int DelY, DelX; //循环变量int Full; //一行是否满的标志for( y = 0; y < ROW - 1; y++ ) //检查第0~22行{Full = 1;for( x = 1; x < COL - 1; x++ ) //检查每行的第1~12列{if( !Map[y][x] ){Full = 0; break;}}if( Full ) //第y行满了,删除该行,该行以上的其他行下移一行{iDeleteRows++; iTotalNum = iDeleteRows*100; //更新得分for( DelY = y; DelY > 0; DelY-- ){for( DelX = 1; DelX < COL - 1; DelX++ )Map[DelY][DelX] = Map[DelY-1][DelX];}for( DelX = 1; DelX < COL - 1; DelX++ ) //第0行置为0Map[0][DelX] = 0;}}}int Rotate( ) //测试旋转是否可行,如果可行则旋转当前方块{int y, x;int TmpBox[4][4];RotateTest( CurrentBox, TmpBox );if( Test( CurrentY, CurrentX, TmpBox ) ){for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = TmpBox[y][x];}return 1;}else return 0;}/*0000 0000 0000 //旋转规律是:Box3[y][x] = Box1[y][3-x] -> 方块绕竖直方向对称变换0100-> 0010-> 0010 //Box2[x][y] = Box3[y][x] -> 沿着主对角线对称变换(相当于矩阵转置)1110 0111 01100000 0000 0010 */int RotateTest( int Box1[4][4], int Box2[4][4] ) //旋转当前方块{ //新增返回值为:旋转后的Box2中最下一个方格所在的行int y, x;for( y = 0; y < 4; y++ ){for( x = 3; x >=0; x-- )Box2[x][y] = Box1[y][3 - x];}for( y=3; y>=0; y-- ) //统计Box2中最下一个方格所在的行{for( x=0; x<4; x++ ){if(Box2[y][x]) break;}if(x<4) break;}return y;}LRESULT CALLBACK WndProc( HWND hwnd, UINT message, //窗口处理函数WPARAM wParam, LPARAM lParam ){HDC hdc, hdcMem;int y, x;PAINTSTRUCT ps;HBITMAP hBitMap;HPEN hPen;HBRUSH hBrush;static int cxClient, cyClient; //窗口客户区宽度和高度char str[20]; //用于显示得分的变量switch( message ){case WM_CREATE:SetTimer( hwnd, tDown, tDownTime, NULL ); //开启两个定时器SetTimer( hwnd, tPaint, tPaintTime, NULL );srand( (unsigned)time( NULL ) );bAuto = false;Pause = false;InitMap( );BuildNextBox( ); //先随机产生一个方块NewFall( ); //方块落下并随机产生下一个方块sprintf( str, " 得分:%d", iTotalNum ); strcat( WindowTxt, str );SetWindowText(hwnd,WindowTxt);return 0;case WM_SIZE:cxClient = LOWORD( lParam ); //取得窗口客户区宽度和高度cyClient = HIWORD( lParam );return 0;case WM_TIMER:switch( wParam ){case tDown: //下降定时器if( !Drop( ) ) //如果不能下降则放置当前方块{PutBox( );MessageBeep( -1 );Clear( ); //清除//刷新得分sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}}break;case tPaint: //重绘定时器InvalidateRect(hwnd, NULL, FALSE); //强制重绘窗口工作区break;}case WM_KEYDOWN:switch( wParam ){case VK_LEFT: //"向左"方向键if(bAuto) break;Move(0); break;case VK_RIGHT: //"向右"方向键if(bAuto) break;Move(1); break;case VK_UP: //"向上"方向键:旋转if(bAuto) break;Rotate( ); break;case VK_DOWN: //"向下"方向键:当前方块下移一行位置if(bAuto) break;MessageBeep( -1 ); Drop( ); break;case VK_RETURN: //回车键:暂停Pause = !Pause;if( Pause ) //暂停、自动求解时也可以暂停KillTimer( hwnd, tDown );else //启动{if(bAuto) SetTimer( hwnd, tDown, tDownTime/5, NULL );else SetTimer( hwnd, tDown, tDownTime, NULL );}break;case VK_SPACE:if(bAuto) break;while( 1 ) //使用永真循环,使得当前方块一直下降到不能下降为止{if( !Drop( ) ){PutBox( ); Clear( );sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}break;}}break;case VK_F1:bAuto = !bAuto;if(bAuto) //自动求解{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime/5, NULL );memcpy( WindowTxt+25, s2, strlen(s2) ); //修改标题}else{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime, NULL );memcpy( WindowTxt+25, s1, strlen(s1) ); //修改标题}SetWindowText(hwnd,WindowTxt);break;}case WM_PAINT: //重绘窗口工作区hdc = BeginPaint( hwnd, &ps );hdcMem = CreateCompatibleDC( hdc );hBitMap = CreateCompatibleBitmap( hdc, cxClient, cyClient );SelectObject( hdcMem, hBitMap );//画地图最外面的矩形(4, 4, 246, 446)Rectangle( hdcMem, StartX + LEN * 1 - 1,StartY + LEN * 1 - 1,StartX + LEN * (COL - 1) + 1, StartY + LEN * (ROW - 1) + 1 );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) );SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(250, 250, 250) );SelectObject( hdcMem, hBrush );for( y = 1; y < ROW - 1; y++ ) //画地图中的每一格{for( x = 1; x < COL - 1; x++ ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX + LEN * (x + 1), StartY + LEN * (y + 1) );}}DeleteObject( hPen );DeleteObject( hBrush );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) ); SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(255, 100, 100) );SelectObject(hdcMem, hBrush);for( y = 1; y < ROW - 1; y++ ) //画出地图中每个被占据的方格{for( x = 1; x < COL - 1; x++ ){if( Map[y][x] ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX +LEN * (x + 1), StartY + LEN * (y + 1) );}}}for( y = 0; y < 4; y++ ) //画当前方块{for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] ){if( y + CurrentY > 0 ){Rectangle( hdcMem, (x + CurrentX) * LEN + StartX,(y + CurrentY) * LEN +StartY,(x + CurrentX + 1) * LEN + StartX,(y + CurrentY + 1) * LEN + StartY );}}}}for( y = 0; y < 4; y++ )//在窗口右边区域画下一个方块{for( x = 0; x < 4; x++ ){if( NextBox[y][x] ){Rectangle( hdcMem, (x + COL) * LEN + StartX,(y + 2) * LEN + StartY,(x+ COL + 1) * LEN + StartX, (y + 3) * LEN + StartY );}}}DeleteObject( hPen );DeleteObject( hBrush );DeleteObject( hBitMap );BitBlt( hdc, 0, 0, cxClient, cyClient, hdcMem, 0, 0, SRCCOPY );DeleteDC( hdcMem );EndPaint( hwnd, &ps );return 0;case WM_DESTROY:KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );PostQuitMessage( 0 );return 0;}//end of switch( message )return DefWindowProc( hwnd, message, wParam, lParam );}。
visual c++ mfc扩展编程实例MFC(Microsoft Foundation Class)是Microsoft提供的一个C++类库,它封装了Windows API,使得开发者可以更方便地使用Windows平台的各种功能。
下面是一个简单的Visual C++ MFC扩展编程实例,演示如何创建一个简单的窗口并显示文本。
1. 打开Visual Studio,创建一个新的MFC应用程序项目。
2. 在项目属性中,将“应用程序类型”设置为“MFC应用程序”。
3. 在“源文件”文件夹中,打开“CMyApp”类。
4. 在“CMyApp”类的“OnInitDialog”函数中,添加以下代码:```cppBOOL CMyApp::OnInitDialog(){CMainDialog::OnInitDialog();// 设置窗口标题SetWindowText(_T("MFC扩展编程实例"));// 创建文本控件CWnd* pWnd = GetDlgItem(IDC_STATIC_TEXT);ASSERT(pWnd);CRect rect;pWnd->GetWindowRect(&rect);CString strText;strText.Format(_T("Hello, MFC!"));pWnd->SetWindowText(strText);return TRUE; // 返回TRUE 除非你对WM_COMMAND 设置了一个处理函数}```5. 在“头文件”文件夹中,打开“CMyApp”类的头文件“CMyApp.h”。
6. 在“CMyApp”类中添加一个成员变量:```cppCStatic m_StaticT ext; // 文本控件成员变量```7. 在“CMyApp”类的构造函数中,初始化该成员变量:```cppCMyApp::CMyApp() : CMainDialog(CMyApp::IDD){// 初始化成员变量m_StaticText.SubclassDlgItem(IDC_STATIC_TEXT, this); // 绑定控件ID 和窗口句柄}```。