MFC中自定義消息

MFC中自定義消息

 

消息映射、循環機制是Windows程序運行的基本方式。VC++ MFC 中有許多現成的消息句柄,可當我們需要完成其它的任務,需要自定義消息,就遇到了一些困難。在MFC ClassWizard中不允許添加用戶自定義消息,所以我們必須手動在程序中添加相應代碼,以便可以象處理其它消息一樣處理自定義消息。

自定義消息的步驟如下(舉個例子):

(1)建立Single Document的MFC Application,工程名爲:MyMessage

(2)自定義消息:

第一步:定義消息

在Resource.h中添加如下代碼:

//推薦用戶自定義消息至少是WM_USER+100,因爲很多新控件也要使用WM_USER消息。

#define WM_MY_MESSAGE (WM_USER+100)

第二步:聲明消息處理函數

選擇CMainFrame類中添加消息處理函數

在MainFrm.h文件中,類CMainFrame內,聲明消息處理函數,代碼如下:

protect:

    afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam);

第三步:實現消息處理函數

在MainFrm.cpp文件中添加如下代碼:

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定義消息:

在Resource.h中將代碼

#define WM_MY_MESSAGE (WM_USER+100)

替換爲:

static UINT WM_MY_MESSAGE=RegisterWindowMessage(_T("User"));

並使用ON_REGISTERED_MESSAGE宏指令取代ON_MESSAGE宏指令,其餘步驟同上。

注:如果仍然使用ON_MESSAGE宏指令,compile可以通過,但是無法響應消息。

當需要使用自定義消息時,可以在相應類中的函數中調用函數PostMessage或SendMessage發送消息PoseMessage(WM_MY_MESSAGE,O,O)。

RegisterWindowMessage Function

The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system.

The message value can be used when sending or posting messages.

Syntax

UINT RegisterWindowMessage(          LPCTSTR lpString

    );

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.

The message remains registered until the session ends.

//如果兩個Application使用相同的string註冊message,他們將等到相同的message值,也就是得到相同的message

 

參考

[1]http://www.cnblogs.com/xulei/archive/2007/11/22/968170.html

[2]http://www.cnblogs.com/pbreak/archive/2010/06/05/1752333.html

[3]MSDN

[4]孫鑫 《VC++ 深入》
轉自:http://www.cnblogs.com/mydomain/archive/2010/09/27/1837103.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章