7
votes

I have the dialog shown with ShowWindow(hWnd, SW_SHOWNOACTIVATE); But it doesn't work, the new dialog still steals the focus, why is it?

here is the some code snippets from my program, QueryWindow is the MFC dialog class linked with the dialog:

QueryWindow window;
//window.DoModal();
window.Create(QueryWindow::IDD);
window.ShowWindow(SW_SHOWNOACTIVATE);
1
Does QueryWindow have an OnInitDialog method? If so, try to return FALSE instead of TRUE at the end of the method.Javier De Pedro
I think we'll need some more code to find out the problem. Could you post the QueryWindow source code? what kind of dialog is it?Javier De Pedro

1 Answers

7
votes

There are few ways to skip dialog from getting focused:

  • Make you OnInitDialog() to return zero value. Example:

    BOOL QueryWindow::OnInitDialog()
    {
        CDialog::OnInitDialog();
    
        return FALSE; // return 0 to tell MFC not to activate dialog window
    }
    

    This is the best and most correct solution.

  • Add WS_EX_NOACTIVATE style to your dialog window. You can edit dialog resource properties or change it in runtime:

    BOOL QueryWindow::PreCreateWindow(CREATESTRUCT& cs)
    {
        cs.dwExStyle |= WS_EX_NOACTIVATE;
    
        return CDialog::PreCreateWindow(cs);
    }
    

    Side-effect: you can use controls on your window, but it will look like it was not activated.

  • Last way is to save foreground window before creating your dialog and set foreground window at the end:

    BOOL QueryWindow::Create(LPCTSTR lpszTemplateName, CWnd* pParentWnd)
    {
        CWnd* pForeground = GetForegroundWindow();
    
        const BOOL bRes = CAlertDialog::Create(lpszTemplateName, pParentWnd);
    
        if(pForeground)
            pForeground->SetForegroundWindow();
        return bRes;
    }
    

    This is the worth solution because potentially you can get flicker.

Important!

Don't forget to control following API calls:

  • ShowWindow - you can use SW_SHOWNOACTIVATE, but can't use SW_SHOW
  • SetWindowPos - add flag SWP_NOACTIVATE