消息處理過程:
1消息定義:
消息簡單的說就是指通過輸入設備向程序發出指令要執行某個操作。具體的某個操作就是已經寫好的代碼,成為消息處理函數。
為何要引進消息映射。一個程序往往擁有多個窗體,主窗口就算一個,其他菜單工具欄等等子窗口,那需要寫多少個switchcase語句,所以MFC采用了消息映射機制,利用一個數組,將窗口消息和相對應的消息處理函數進行映射,可以理解成這個是一個表,該機制叫消息映射
AFX_MSGMAP可以得到基類的消息映射入口地址和得到本身的消息映射入口地址。
2消息種類:
(1)windows消息,主要包含WM_開頭的消息,WM_COMMAND消息除外,由窗口和視圖處理,此類消息帶有確定如何處理消息的參數。
(2)控件通知,此類消息包含從控件和其他子窗口發送到其父窗口的WM_COMMAND通知消息,
(3)命令消息,包含了用戶界面對象發出的WM_COMMAND通知消息,
其中windows消息和控件通知消息由窗口來處理,CFrameWnd,CMDIFrameWnd,CMDIChildWnd,CView,CDialog
命令消息更廣的是對象處理
形式如下:ON_COMMAND(id,memberFxn);
對于通知消息,例如樹形控件是ON_CONTROL(EN_CHANGE,id,memberFxn);
3消息處理過程
MFC消息處理過程如下:
(1)_AfxCbtFilterHook()截獲消息(這個是一個鉤子函數);
(2)_AfxCbtFilterHook()把窗口過程設定為AfxWndProc();
(3)函數AfxWndProc()接收windows操作系統的發送的消息。
(4)函數AfxWndProc()調用函數AfxCallWndProc()進行消息處理;
(5)函數AfxCallWndProc()調用CWnd類的方法WindowProc進行消息處理。
4添加用戶自定義消息處理函數
第一步,定義消息,#define WM_MYMESSAGE (WM_USER+100)
第二步,實現消息處理函數,該函數使用WPRAM和LPARAM參數,并返回LPRESULT
LPRESULT CMainFrame::OnMyMessage(WPARAM wParam,LPARAM lParam)
{
return 0;
}
第三步:在類頭文件中的FX_MSG塊中說明消息處理函數
形式如下
afx_msg LRESULT OnMyMessage(WPARAM wParam,LPARAM lParam)
第四步。在用戶類的消息塊中,使用ON_MESSAGE宏指令將消息映射到消息處理函數中。
ON_MESSAGE(WM_MYMESSAGE,OnMyMessage)
可以看出來,用戶定義的消息和通過classwizard添加的消息一樣。
5windows消息循環機制
windows消息函數
從消息隊列中取出消息
在MSDN中PeekMessage的定義
BOOL PeekMessage
The PeekMessage function checks a thread message queue for a message and places the message (if any) in the specified structure.
BOOL PeekMessage(
LPMSG lpMsg, // pointer to structure for message
HWND hWnd, // handle to window
UINT wMsgFilterMin, // first message
UINT wMsgFilterMax, // last message
UINT wRemoveMsg // removal flags
);
從線程消息隊列中取出一個消息
GetMessage
The GetMessage function retrieves a message from the calling thread's message queue and places it in the specified structure. This function can retrieve both messages associated with a specified window and thread messages posted via the PostThreadMessage function. The function retrieves messages that lie within a specified range of message values. GetMessage does not retrieve messages for windows that belong to other threads or applications.
BOOL GetMessage(
LPMSG lpMsg, // address of structure with message
HWND hWnd, // handle of window
UINT wMsgFilterMin, // first message
UINT wMsgFilterMax // last message
);
如果把2,3,4設置為null或者0,表示接受本程序的所有消息
還要注意上面兩者的區別,
都是比較基礎的東西,
posted on 2011-09-25 10:43
mengkai 閱讀(301)
評論(0) 編輯 收藏 引用