how to project my window as active window on foreground
There were some windows opened, And from my process I want to launch one more window(high priority) in which user has to enter cr开发者_高级运维edentials. And i want to put this credentials window to foreground, in turn it might give good experience to user as he need not manually select the credentials window. And this is one time launching, definitely not annoying but compulsory for user to enter creds.
what is the best way to achieve this? I don't think simulating mouse click is good idea. Is there a way to send msg to rest of windows to lose their focus? so that when i launch my window, it will come foreground.
This works for me without having to use SetWindowPos
to make the window 'always on top':
HWND foreGround = GetForegroundWindow();
if (foreGround != m_hWnd)
{
if (!::SetForegroundWindow(m_hWnd))
{
if (!foreGround)
{
foreGround = FindWindow(_T("Shell_TrayWnd"), NULL);
}
DWORD idForeground = GetWindowThreadProcessId(foreGround, NULL);
DWORD idTarget = GetWindowThreadProcessId(m_hWnd, NULL);
AttachThreadInput(idForeground, idTarget, TRUE);
::SetForegroundWindow(m_hWnd);
AttachThreadInput(idForeground, idTarget, FALSE);
}
BringWindowToTop();
}
I use this in a chat application so a new chat message can steal focus (optional obviously as some users don't like this.)
You need to call SetWindowPos with wndTopMost
parameter to set your window at the top of all other windows.
This UI pattern (window to enter mandatory values) is commonly known as a modal dialog. In MFC, you'd look for CDialog::DoModal
. I.e. you derive your credential window from CDialog
, and then call the inherited DoModal
method.
A modal dialog blocks user input in other windows in your app, and therefore is automatically moved before the blocked windows.
Users expect programs to only come to the foreground when they are supposed to. This technique enables programs to violate that contract, stealing foreground and subverting the design. Do not apply this without considering other options. For example using the owner window relationship between related windows and passing the ability to become foreground, when needed, using AllowSetForegroundWindow().
精彩评论