Modeless Dialogs

Why doesn't my modeless WTL dialog act like a dialog? This is old hat for any MFC programmer, but it took me a little bit to get it right.

First, start out with a dialog that works great as a modal dialog:

class CIMDialog : public CAxDialogImpl<CIMDialog>,
    public CDialogResize<CIMDialog>
{ etc....

When it's created modelessly it doesn't behave quite right:

CIMDialog *d = new CIMDialog();
d->Create(NULL);
d->CenterWindow(m_hWnd);
d->ShowWindow(SW_SHOWNORMAL);

When you press tab while one of its controls has focus, nothing happens. Accelerators don't do anything, either. The solution is to wire it into the main message loop:

class CIMDialog : public CAxDialogImpl<CIMDialog>,
    public CDialogResize<CIMDialog>,
    public CMessageFilter

{
    ...

    virtual BOOL PreTranslateMessage(MSG* pMsg) {
        return IsDialogMessage(pMsg);
    }

    ...

    LRESULT OnInitDialog(UINT uMsg,
        WPARAM wParam,
        LPARAM lParam,
        BOOL& bHandled)
    {
        ...
        
        // register object for message filtering
        CMessageLoop* pLoop = _Module.GetMessageLoop();
        ATLASSERT(pLoop != NULL);
        pLoop->AddMessageFilter(this);

        ...
    }

    virtual void OnFinalMessage(HWND /*hWnd*/)
    {
        CMessageLoop* pLoop = _Module.GetMessageLoop();
        pLoop->RemoveMessageFilter(this);
        delete this;
    }

Categories

About this Entry

This page contains a single entry by Mike Tsao published on January 19, 2004 10:20 PM.

Close Elections was the previous entry in this blog.

Mars Rover dead? is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.2-en