mfc - 带有自定义参数的sendmessage / postmessage

时间:2013-03-25 08:20:58

标签: c++ mfc sendmessage

我想在MFC中有一个消息处理程序,它接受我在消息映射中定义的任何参数。

例如,

static UINT UWM_STATUS_MSG = RegisterWindowMessage("Status message");
static UINT UWM_GOT_RESULT= RegisterWindowMessage("Result has been obtained");

//{{AFX_MSG(MyClass)
    afx_msg void OnCustomStringMessage(LPCTSTR);
    afx_msg void OnStatusMessage();
//}}AFX_MSG


BEGIN_MESSAGE_MAP(MyClass, CDialog)
    //{{AFX_MSG_MAP(MyClass)
        ON_REGISTERED_MESSAGE(UWM_STATUS_MSG, OnStatusMessage)
        ON_REGISTERED_MESSAGE(UWM_GOT_RESULT, OnCustomStringMessage)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

void MyClass::OnCustomStringMessage(LPCTSTR result)
{
    m_result.SetWindowText(result);
}

void MyClass::OnStatusMessage()
{
    // Do something
}

DWORD WINAPI MyClass::thread(LPVOID lParam)
{
    char result[256] = { 0 };
    SendMessage(UWM_STATUS_MSG);

    // Do some stuff and store the result

    PostMessage(UWM_GOT_RESULT, result);
}

这样的事情可能吗?

3 个答案:

答案 0 :(得分:1)

通过ON_MESSAGE或ON_REGISTERED_MESSAGE调用的成员函数的签名必须是:

afx_msg LRESULT OnMyFunction(WPARAM p1,LPARAM p2);

你必须使用强制转换操作符处理它。

因此你应该这样写:

...
afx_msg LRESULT OnCustomStringMessage(WPARAM p1, LPARAM p2);
...

LRESULT MyClass::OnCustomStringMessage(WPARAM p1, LPARAM p2)
{
  LPCTSTR result = (LPCTSTR)p1 ;
   m_result.SetWindowText(result);
}

DWORD WINAPI MyClass::thread(LPVOID lParam)
{
    static char result[256] = { 0 };   // we need a static here
                                       // (see explanations from previous answers)
    SendMessage(UWM_STATUS_MSG);

    // Do some stuff and store the result

    PostMessage(UWM_GOT_RESULT, (WPARAM)result);
}

如果要从几个不同的线程调用MyClass :: thread,则需要以更加复杂的方式处理 result 数组,只需将其声明为静态,例如在MyClass中分配数组:: thread ands在OnCustomStringMessage中删除它,如user2173190的回答所示。

答案 1 :(得分:0)

尝试使用WM_USER消息作为自定义消息,并通过覆盖它来在OnMessage方法中处理它。要了解WM_USER消息,请参阅here

答案 2 :(得分:0)

如果将WM_USER下面的消息发送到异步消息函数(PostMessage,SendNotifyMessage和SendMessageCallback),则其消息参数不能包含指针。否则,操作将失败。函数将在接收线程有机会处理消息之前返回,并且发送方将在使用之前释放内存。

PostMessage的消息参数可以包含指针 您可以将指针包含为参数。将它们作为整数强制转换,不要在激活PostMessage的线程或函数上处理或释放它们,而是在接收线程或函数上处理或释放它们。 只需确保在使用指针时,只对一条消息使用一种指针类型,不要将指针混合到具有相同消息的不同对象。

http://msdn.microsoft.com/zh-cn/library/windows/desktop/ms644944(v=vs.85).aspx