簡體   English   中英

等價於MFC Windows的OnFinalMessage嗎?

[英]Equivalent of OnFinalMessage for MFC windows?

ATL CWindow類具有一個有用的虛擬方法OnFinalMessage ,在處理該窗口的最后一個窗口消息之后將調用該方法-此時可以安全地銷毀或刪除與該窗口關聯的任何對象。 從MFC CWnd類派生的Windows是否有等效的窗口?

您正在尋找PostNcDestroy()

順便說一句,如果您要實現無模式對話框,並且正在尋找“刪除此內容”的位置,那么PostNcDestroy()就是這里。

這個答案描述了我最終如何解決我的問題。 我會注意到,盡管John Dibling的回答很有幫助,但這並不是解決我的問題的最終方法。 這是因為WM_NC_DESTROY消息是作為最終消息發送到窗口的,但是可以在完成對窗口的最后一條消息之前對其進行處理。 請參閱例如http://support.microsoft.com/?kbid=202110 ,以獲取有關該問題的說明。

  1. 使用WM_CLOSE調用DialogProc()。
  2. ProcessWindowMessage()調用WM_CLOSE處理程序。
  3. 在WM_CLOSE處理程序中,調用DestroyWindow()。
  4. 這樣最終用WM_NCDESTROY再次調用DialogProc。
  5. ProcessWindowMessage()調用您的WM_NCDESTROY處理程序。
  6. 您在WM_NCDESTROY處理程序中調用“刪除此”。

調用delete this ,該對象不再有效,但是從技術上講,您仍然在WM_CLOSE處理程序中,因此當您最終回到那里時,可能會崩潰。 這意味着假設您確實可以在PostNcDestroy中delete this它並不安全,因為該對象可能仍然存在於其他堆棧框架中。

/// 
/// A window designed to allow any window to use the "OnFinalMessage" method from the ATL CWindow class
/// You must call SubclassWindow for this instance so that the window procedure runs
template<class T>
class FinalMessageWindow : public CWindowImpl<FinalMessageWindow<T> >
{
    T *_t; /// The object wanting to receive the final message notification
public:
    BEGIN_MSG_MAP(FinalMessageWindow<T>)
    END_MSG_MAP()

    /// 
    /// The constructor
    /// \param t The object that wants to get the OnFinalMessage notification
    FinalMessageWindow(T *t)
        : _t(t)
    {
    }

    /// 
    /// Called when the final window message for the window has been processed - this is often a good time to delete the object
    /// \param hWnd The window handle
    virtual void OnFinalMessage(HWND hWnd)
    {
        _t->OnFinalMessage(hWnd);
    }
};

我創建了上面的類,請注意,它是從ATL CWindow類派生的-這使我可以對該類使用OnFinalMessage處理程序。 OnFinalMessage處理程序與MFC窗口中的PostNcDestroy的不同之處在於,它保證僅在堆棧上的最終消息處理程序完成后才被調用。

然后,我們使用窗口子類化將此窗口作為我自己窗口的窗口過程插入:

// roughly speaking
FinalMessageWindow<MyWindow> _finalMessageWindow(this);
finalMessageWindow.SubclassWindow(m_hWnd);

然后,我們為窗口實現OnFinalMessage處理程序:

void MyWindow::OnFinalMessage(HWND hWnd)
{
    delete this;
}

暫無
暫無

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

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