I have a window that is shown from a WPF application using the ShowDialog()
method. Inside this dialog window, I need to call the native SetForegroundWindow
to bring some other app in the foreground, and then I need to call SetForegroundWindow
again to bring this window back into the foreground.
The dialog window can be opened using a button (that has a command binding) or a key (KeyUp event is handled and ShowDialog()
is called).
Everything works fine when the button is clicked (the dialog is shown -> the other application is brought into the foreground -> the dialog is brought into the foreground again). However, when the key is used, the dialog window is no longer brought into the foreground after SetForegroundWindow
is used on the other application and the taskbar is flashing orange (indicating that the window requested foreground, but Windows blocked it because it thought that the dialog window is trying to steal focus).
This is the code that I am using when opening the dialog window:
try
{
await BringApplicationIntoForegroundAsync(hWnd); // this code brings application into foreground at some point
// do some work
}
finally
{
SetForegroundWindow(hWnd);
}
If I send any key or click on the dialog window before calling BringApplicationIntoForegroundAsync(hWnd)
everything works fine (even if the dialog was opened using a key).
If the dialog is opened using a key and the user does not interact with it before the first SetForegroundWindow
, the second SetForegroundWindow
does not work (returns false
).
My guess is that when the button is used to open the dialog, somehow the dialog receives input and Windows allows it to call SetForegroundWindow
the second time.