MFC customizes the implementation of the message

  • 2020-04-02 02:25:32
  • OfStack

I. overview:

Message mechanism is a typical running mechanism of Windows programs. There are many encapsulated messages in MFC, such as WM_BTN**. However, there are some special cases where we need to customize some messages to perform the functions we need, and the MFC wizard cannot help us to do this. We can do this by adding code.

Ii. Implementation method

Add custom message operation as follows:
1. Set up MFC project, such as dialog box based application, Test.
2. Add the value of the message to be processed in the resource, that is, add the following code in ctestdlg.h. (since many MFC messages are in WM_USER, we use a larger message than WM_USER.)


 #define WM_MyMessage (WM_USER+100)

3. Declare the message handler function and add the following code in ctestdlg.h:


class CTestDlg : public CDialog
{ 
protected:
  ... 
  //The generated message mapping function
   ... 
  afx_msg LRESULT OnMyMessage(WPARAM wParam, LPARAM lParam); // add lyw
  DECLARE_MESSAGE_MAP()
   ... 

4. Add message mapping processing, find the following section in ctestdlg.cpp, add code:
 


BEGIN_MESSAGE_MAP(CTestDlg, CDialog)
    ... 
  ON_MESSAGE(WM_MyMessage, OnMyMessage)
END_MESSAGE_MAP()

  5. Implement your own custom message handling:
 


LRESULT CTestDlg::OnMyMessage(WPARAM wParam, LPARAM lParam)
{
  //MessageBox("recv msg success");
  //Add your own message handling
   ... 
  return 0;  
}

6. If you want to send a custom message, you need to use code
 


SendMessage( WM_MyMessage, 0, 0);

or


 PostMessage(WM_MyMessage, 0, 0); 

If you want to define system-unique messages for multiple applications to process, the difference is as follows:

1. Replace the macro #define WM_MyMessage (WM_USER+100) in step 2 above with the following code:


 static UINT WM_MyMessage = RegisterWindowMessage("myMessage");

2. Replace the code in the 4 steps above with the following:


 BEGIN_MESSAGE_MAP(CTestDlg, CDialog)
    ... 
  ON_REGISTERED_MESSAGE(WM_MyMessage, OnMyMessage)
END_MESSAGE_MAP()

3. When testing a message, if you want multiple applications to receive the message, you need to use:


 ::SendMessage(HWND_BROADCAST, WM_MyMessage, 0, 0);

Related articles: