Basics for catching a windows message manually

In the following sample, we catch the WM_RBUTTONDOWN message. This would work for any windows message :

  1. In the AFX_MSG section of your .h file, add the declaration of your message handler function :
     //{{AFX_MSG(CMyCtrl)
    // NOTE – the ClassWizard will add and remove member functions here.
    afx_msg LRESULT OnRBtnDown(WPARAM wParam, LPARAM lParam); // handler function
    //}}AFX_MSG
  2. Add the body of your function in your .cpp file :
    LRESULT CMyCtrl::OnRBtnDown(WPARAM wParam, LPARAM lParam)
    {
    AfxMessageBox(“WM_RBUTTONDOWN caught”);
    return 0;
    } // LRESULT CMyCtrl::OnRBtnDown
  3. In the message map of your .cpp file, add the following :
    BEGIN_MESSAGE_MAP(CMyCtrl, CWnd)
    //{{AFX_MSG_MAP(CFilteredListCtrl)
    // NOTE – the ClassWizard will add and remove mapping macros here.
    ON_MESSAGE(WM_RBUTTONDOWN, OnRBtnDown)
    //}}AFX_MSG_MAP
    END_MESSAGE_MAP()

However, some shortcuts allows you to take care of standard messages. For example, the WM_RBUTTONDOWN message can be caught with :

  1. //{{AFX_MSG(CMyCtrl)
    // NOTE – the ClassWizard will add and remove member functions here.
    afx_msg void OnRButtonDown( UINT nFlags, CPoint point );
    //}}AFX_MSG
  2. void CMyCtrl::OnRButtonDown( UINT nFlags, CPoint point )
    {
    CWnd::OnRButtonDown( nFlags, point );
    } // void CMyCtrl::OnRButtonDown
  3. BEGIN_MESSAGE_MAP(CMyCtrl, CWnd)
    //{{AFX_MSG_MAP(CMyCtrl)
    // NOTE – the ClassWizard will add and remove mapping macros here.
    ON_WM_RBUTTONDOWN()
    //}}AFX_MSG_MAP
    END_MESSAGE_MAP()

You can apply the same approach to many WM_XXX messages.

Leave a Reply

Your email address will not be published. Required fields are marked *