消息映射、循环机制是Windows程序运行的基本方式。VC++ MFC 中有许多现成的消息句柄,可当我们需要完成其它的任务,需要自定义消息, 自定义消息的步骤如下: //推荐用户自定义消息至少是WM_USER+100,因为很多新控件也要使用WM_USER消息。
#define WM_MY_MESSAGE (WM_USER+100) 第二步:声明消息处理函数 protect:
afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam); 第三步:实现消息处理函数 LRESULT CMainFrame::OnMyMessage(WPARAM wParam, LPARAM lParam)
{ //TODO: Add your message handle code return 0; } 第四步:在CMainFrame类的消息块中,使用ON_MESSAGE宏指令将消息映射到消息处理函数中 BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE() ON_MESSAGE(WM_MY_MESSAGE,OnMyMessage) //ON_REGISTERED_MESSAGE (WM_MY_MESSAGE,OnMyMessage) END_MESSAGE_MAP() 如果用户需要一个定义整个系统唯一的消息,可以调用SDK函数RegisterWindowMessage定义消息: #define WM_MY_MESSAGE (WM_USER+100)
替换为: static UINT WM_MY_MESSAGE=RegisterWindowMessage(_T("User"));
并使用ON_REGISTERED_MESSAGE宏指令取代ON_MESSAGE宏指令,其余步骤同上。 附:RegisterWindowMessage函数说明 RegisterWindowMessage Function -------------------------------------------------------------------------------- The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. Syntax UINT RegisterWindowMessage( LPCTSTR lpString
); Parameters lpString If the message is successfully registered, the return value is a message identifier in the range 0xC000 through 0xFFFF. If the function fails, the return value is zero. To get extended error information, call GetLastError. Remarks The RegisterWindowMessage function is typically used to register messages for communicating between two cooperating applications. If two different applications register the same message string, the applications return the same message value. |
|