1
votes

In my MFC SDI application, In the document section derived from CDocument, I have added a user message handler for posting messages as follows. I get the compilation error:

error C2440: 'static_cast' : cannot convert from 'void (__thiscall CMyDoc::* )(WPARAM,LPARAM)' to 'LRESULT (__thiscall CWnd::* )(WPARAM,LPARAM)' .

CMyDoc.cpp:

#define UWM_Message1 (WM_APP+1)

BEGIN_MESSAGE_MAP(CMyDoc, CDocument)
    //{{AFX_MSG_MAP(CMyDoc)
        // NOTE - the ClassWizard will add and remove mapping macros here.
        //    DO NOT EDIT what you see in these blocks of generated code!
    ON_MESSAGE(UWM_Message1, &CMyDoc::OnMyFunc)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()


void CMyDoc::OnMyFunc(WPARAM wParam, LPARAM lParam)
{
    int Len = (int)wParam;
    BYTE * pBuf  = (BYTE*)lParam;
    //do stuff..

    return;
}

CMyDoc.h:

inside the class CMyDoc:

public:
    afx_msg void OnMyFunc(WPARAM wParam, LPARAM lParam);
1

1 Answers

1
votes

You can't use ON_MESSAGE in a CDocument derived class. ON_MESSAGE requires a function of a CWnd derived class(as the compiler error indicates). There's no HWND to SendMessage/PostMessage to either when in the doc. Catch the message in the view or frame and forward it to the (active) document. The view supports GetDocument() to return a pointer to the document, then call the function directly.

Also, the prototype is incorrect, should be afx_msg LRESULT func(WPARAM, LPARAM)

EDIT: Added example code as requested

In your view class header file: afx_msg LRESULT OnMyFunc(WPARAM, LPARAM)

In your view cpp file, within the message map:

BEGIN_MESSAGE_MAP(CMyView, CView) //{{AFX_MSG_MAP(CMyView) ON_MESSAGE(UWM_Message1, &CMyView::OnMyFunc) //}}AFX_MSG_MAP END_MESSAGE_MAP()

Then somewhere in your view cpp file:

LRESULT CMyView::OnMyFunc(WPARAM wParam, LPARAM lParam) { GetDocument()->MyFunc(wParam, lParam); return 0; }

In your document class, just add a public member "MyFunc" function like you'd normally do and do all your processing there. If you can't piece this together, I can upload an example project.

2nd EDIT: in your doc class

POSITION pos = GetFirstViewPosition();
if(pos != NULL) {
    CView* pView = GetNextView(pos);
    PostMessage(pView->GetSafeHwnd(), WM_YOUR_MESSAGE, wparam, lparam);
}