标签:笔记 事件处理
主要内容:
使程序能够响应菜单事件和鼠标事件(按下左键、移动、松开左键)。
关于事件:
视窗程序通过事件进行用户进行交互。当用户进行单击鼠标、选择菜单、按下键盘等操作时都会产生一个事件。在程序中,我们需要:1,为指定的事件编写处理程序;2.将事件处理程序进行注册。
编写事件处理程序
编写事件处理程序其实就是为处理事件的类添加一个方法(即成员函数)。在MFC中,无论是视窗框架类(如CFrameWnd,CMDIFrameWnd,CMDIChildWnd),还是文档类,或者视图类,都可以处理事件,我们只需要在类中添加相应的方法即可。
由于事件处理程序是特殊的方法,所以事件处理程序必须要以afx_msg开头。
事件处理程序注册
要处理事件的类,在类体中除了要添加负责处理事件的方法外,还要:1,在类体中添加以下宏DECLARE_MESSAGE_MAP();2,在类体外添加事件处理程序注册宏,格式如下:
BEGIN_MESSAGE_MAP(类名,父类名)
具体的事件注册宏
END_MESSAGE_MAP()
程序代码:
#include <afxwin.h>
#include "Message.h"
class CMyFrame : public CFrameWnd
{
private:
CMenu *pMenu;
public:
CMyFrame()
{
Create(NULL, "Hello MFC");
pMenu = new CMenu;
pMenu->LoadMenu(IDR_MENU1);
SetMenu(pMenu);
}
~CMyFrame()
{
delete pMenu;
}
afx_msg void OnExit()
{
MessageBox("Exit1");
DestroyWindow();
}
afx_msg void OnLButtonDown(UINT nFlags, CPoint point)
{
SetCapture();
}
afx_msg void OnMouseMove(UINT nFlags, CPoint point)
{
if(GetCapture() == this)
{
CClientDC aDC(this);
aDC.SetPixel(point, RGB(255, 0, 0));
}
}
afx_msg void OnLButtonUp(UINT nFlags, CPoint point)
{
ReleaseCapture();
}
DECLARE_MESSAGE_MAP()
};
BEGIN_MESSAGE_MAP(CMyFrame, CFrameWnd)
ON_COMMAND(ID_Exit1, OnExit)
ON_WM_LBUTTONDOWN()
ON_WM_MOUSEMOVE()
ON_WM_LBUTTONUP()
END_MESSAGE_MAP()
class CMyApp : public CWinApp
{
public:
BOOL InitInstance()
{
CFrameWnd *pFrame = new CMyFrame;
m_pMainWnd = pFrame;
pFrame->ShowWindow(SW_SHOW);
return true;
}
}a_app;。。。
标签:笔记 事件处理
原文地址:http://3677403.blog.51cto.com/3667403/1655304