文章編號: 142415 - 上次校閱: 2003年12月9日 - 版次: 2.0

PRB: MFC 訊息處理常式不使用 PostThreadMessage() 呼叫

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。

在此頁中

全部展開 | 全部摺疊

徵狀

當程式碼使用 PostThreadMessage() Win32 函式時,都不會呼叫 MFC 訊息處理常式。

發生的原因

當您呼叫 PostThreadMessage() 時,訊息會放置在執行緒的訊息佇列。不過,因為張貼這種方式的訊息不是與視窗相關聯的 MFC 會不分派它們到訊息或命令處理常式。 為了要處理這些訊息、 覆寫您的 CWinApp 衍生類別,PreTranslateMessage() 函式及手動處理訊息。

解決方案

下列程式碼會示範如何呼叫 PostThreadMessage() InitInstance() 使用單一執行緒應用程式之 CWinApp 衍生類別中。只不過這裡顯示的程式碼會讓替代 CWinThread 衍生類別中,原則就是相同的次要執行緒。

Visual C++ 4.2 並支援張貼到執行緒的處理訊息。如需詳細資訊請參閱 Visual C++ 4.2 文件中的 ON_THREAD_MESSAGE。

注意: MFC 背景工作執行緒並沒有一個訊息迴圈幫/浦與其相關,因此您必須使用使用者介面執行緒。

範例程式碼

/* Compile options needed:

   standard MFC project generated by AppWizard */ 

BOOL CThreadMsgApp::PreTranslateMessage(MSG* pMsg)
{
    // Is it the Message you want?
    // You can use a switch statement but because this is
    // only looking for one message, you can use the if/else
    if (pMsg->message == WM_USER+2268)
    {
        // Call the function to handle this message
   OnReceivedCommand(pMsg->wParam,pMsg->lParam);
        // Tell MFC no more processing is needed
        return TRUE;
    }
    else
        // Call MFC to have it continue processing the message
        return CWinThread::PreTranslateMessage(pMsg);
}

BOOL CThreadMsgApp::InitInstance()
{
    WPARAM wParam;
    LPARAM lParam;
    wParam = MAKEWPARAM(0,0); // We can put whatever we
    lParam = MAKELPARAM(0,0); // want in wParam & lParam

    // Send the user-defined Thread Message
    // m_nThreadID is a member of CWinThread that holds the thread ID
    PostThreadMessage(m_nThreadID, WM_USER+2268, wParam, lParam);

    return TRUE;
}

void CThreadMsgApp::OnReceivedCommand(WPARAM wParam, LPARAM lParam)
{
    // You can do whatever you want in here, this is simply
    // sending output to the debug window
    TRACE0("Received WM_USER+2268!!\n");
}
				

?考

如需有關 CWinThread 物件的詳細資訊,請參閱下列: MFC 百科、 多執行緒: 建立使用者介面執行緒。

這篇文章中的資訊適用於:
  • Microsoft Visual C++ 1.0 Professional Edition
  • Microsoft Visual C++ 2.0 Professional Edition
  • Microsoft Visual C++ 2.1
  • Microsoft Visual C++ 2.2
  • Microsoft Visual C++ 4.0 Standard Edition
  • Microsoft Visual C++ 4.1 Subscription
關鍵字:?
kbmt kbprb kbthread KB142415 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:142415? (http://support.microsoft.com/kb/142415/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。
Retired KB Article依現狀不再更新的知識庫內容免責聲明
本文旨在說明 Microsoft 不再提供支援的產品。因此,本文係依「現狀」提供,不會再更新。