MFC 定时器编程实验
一、实验目的
(1) 掌握Visual Studio 开发环境调试程序的方法; (2) 掌握MFC 消息映射的操作步骤;
(3) 掌握MFC 编程模式中定时器的使用方法.
二、实验内容
设计一个窗口,在窗口中间位置绘制一个红色粗实线的矩形,并用交替使用三种不同样式的画刷填充矩形的内部,每次刷新的时间间隔为1.0 秒。 单击鼠标左键启动定时器,单击鼠标右键停止定时器。
三、程序清单
1.头文件
#include \
class CDemoWnd:public CFrameWnd {
public:
CDemoWnd(); ~CDemoWnd(); public:
LRESULT OnPaint(WPARAM wParam,LPARAM lParam); LRESULT OnTimer(WPARAM wParam,LPARAM lParam);
LRESULT OnLButtonDown(WPARAM wParam,LPARAM lParam); LRESULT OnRButtonDown(WPARAM wParam,LPARAM lParam); DECLARE_MESSAGE_MAP() public:
int m_nState; };
class CDemoApp:public CWinApp {
public:
BOOL InitInstance(); };
CDemoApp theApp; 2.源文件
#include \
CDemoWnd::CDemoWnd() // 构造函数 { m_nState = 0; }
CDemoWnd::~CDemoWnd() // 析构函数 { }
BEGIN_MESSAGE_MAP(CDemoWnd,CFrameWnd) ON_MESSAGE(WM_PAINT,OnPaint) ON_MESSAGE(WM_TIMER,OnTimer)
ON_MESSAGE(WM_LBUTTONDOWN,OnLButtonDown) ON_MESSAGE(WM_RBUTTONDOWN,OnRButtonDown) END_MESSAGE_MAP()
LRESULT CDemoWnd::OnLButtonDown(WPARAM wParam,LPARAM lParam) { SetTimer(1,1000,NULL); return 0; }
LRESULT CDemoWnd::OnRButtonDown(WPARAM wParam,LPARAM lParam) { KillTimer(1); return 0; }
LRESULT CDemoWnd::OnPaint(WPARAM wParam,LPARAM lParam) { CPaintDC dc(this); CPen Pen, *poldpen; CBrush Brush, *pOldBrush; switch (m_nState) { case 0: Brush.CreateSolidBrush(RGB(0, 150, 255)); //紫色 m_nState = 1; break; case 1: Brush.CreateSolidBrush(RGB(0, 255, 100)); //蓝色 m_nState = 2; break; case 2: Brush.CreateSolidBrush(RGB(200, 0, 200)); //青色 m_nState = 0; break; } pOldBrush = dc.SelectObject(&Brush); Pen.CreatePen(PS_SOLID, 3, RGB(255, 0, 0)); poldpen = dc.SelectObject(&Pen); dc.Rectangle(300, 100, 800, 500); dc.SelectObject(poldpen); dc.SelectObject(pOldBrush); return 0; }
LRESULT CDemoWnd::OnTimer(WPARAM wParam,LPARAM lParam) { CRect rt(40, 40, 1000, 1000);
InvalidateRect(&rt); return 0; }
BOOL CDemoApp::InitInstance() { CDemoWnd *pMainWnd = new CDemoWnd(); pMainWnd->Create(NULL,\ pMainWnd->ShowWindow(m_nCmdShow); pMainWnd->UpdateWindow(); m_pMainWnd = pMainWnd; return TRUE; }
四、运行结果