I\'m using SetForegroundWindow API in .NET using PInvoke.
When I use the API while debugging in Visual Studio its works perfectly. But it doesn\'t work always when
The trick is to 'fool' windows (not trying to talk in pleonasms) and attach the input to the new thread to which the window-to-focus belongs, I took most of this from the pinvoke website but added a test to restore minimized windows:
private const uint WS_MINIMIZE = 0x20000000;
private const uint SW_SHOW = 0x05;
private const uint SW_MINIMIZE = 0x06;
private const uint SW_RESTORE = 0x09;
public static void FocusWindow(IntPtr focusOnWindowHandle)
{
int style = GetWindowLong(focusOnWindowHandle, GWL_STYLE);
// Minimize and restore to be able to make it active.
if ((style & WS_MINIMIZE) == WS_MINIMIZE)
{
ShowWindow(focusOnWindowHandle, SW_RESTORE);
}
uint currentlyFocusedWindowProcessId = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
uint appThread = GetCurrentThreadId();
if (currentlyFocusedWindowProcessId != appThread)
{
AttachThreadInput(currentlyFocusedWindowProcessId, appThread, true);
BringWindowToTop(focusOnWindowHandle);
ShowWindow(focusOnWindowHandle, SW_SHOW);
AttachThreadInput(currentlyFocusedWindowProcessId, appThread, false);
}
else
{
BringWindowToTop(focusOnWindowHandle);
ShowWindow(focusOnWindowHandle, SW_SHOW);
}
}