简体   繁体   中英

How to show a MFC dialog without stealing focus on the other window

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM