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, Q开发者_Go百科ueryWindow 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
精彩评论