簡體   English   中英

mfc-具有自定義參數的sendmessage / postmessage

[英]mfc - sendmessage/postmessage with custom parameters

我想在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);
}

這樣的事情可能嗎?

通過ON_MESSAGE或ON_register_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,則需要以一種更加編譯的方式處理結果數組,即僅聲明它為靜態,例如,在MyClass :: thread中分配該數組,然后按照建議在OnCustomStringMessage中將其刪除由user2173190的答案。

嘗試將WM_USER消息用作您的自定義消息,並通過覆蓋它在OnMessage方法中對其進行處理。 要了解有關WM_USER消息的信息,請參見此處

如果將WM_USER以下范圍內的消息發送給異步消息函數(PostMessage,SendNotifyMessage和SendMessageCallback),則其消息參數不能包含指針。 否則,操作將失敗。 該函數將在接收線程有機會處理該消息之前返回,並且發件人將在使用該消息之前釋放內存。

PostMessage的消息參數可以包含指針您可以包含指針作為參數。 將它們強制轉換為整數,不要在觸發PostMessage的線程或函數上處置或釋放它們,而在接收線程或函數上處置或釋放它們。 只要確保使用指針時,您只對一條消息使用一種指針類型,就不要將指向同一消息的不同對象的指針混合使用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM