Hi, had the same problem, hope this will help:
The trick is to make windows ‘think’ that our process and the target window (hwnd) are related by attaching the threads (using AttachThreadInput API) and using an alternative API: BringWindowToTop.
Forcing Window/Internet Explorer to the foreground:
private static void ForceForegroundWindow(IntPtr hWnd)
{
uint foreThread = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
uint appThread = GetCurrentThreadId();
const uint SW_SHOW = 5;
if (foreThread != appThread)
{
AttachThreadInput(foreThread, appThread, true);
BringWindowToTop(hWnd);
ShowWindow(hWnd, SW_SHOW);
AttachThreadInput(foreThread, appThread, false);
}
else
{
BringWindowToTop(hWnd);
ShowWindow(hWnd, SW_SHOW);
}
}
A more advanced implementation of AttachedThreadInputAction pattern
The idea is to attach to the target process thread and preform an action.
Code Snippet
public static void AttachedThreadInputAction(Action action)
{
var foreThread = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);
var appThread = GetCurrentThreadId();
bool threadsAttached = false;
try
{
threadsAttached =
foreThread == appThread ||
AttachThreadInput(foreThread, appThread, true);
if (threadsAttached) action();
else throw new ThreadStateException("AttachThreadInput failed.");
}
finally
{
if (threadsAttached)
AttachThreadInput(foreThread, appThread, false);
}
}
Usage
Code Snippet
public const uint SW_SHOW = 5;
public static void ForceWindowToForeground(IntPtr hwnd)
{
AttachedThreadInputAction(
() =>
{
BringWindowToTop(hwnd);
ShowWindow(hwnd, SW_SHOW);
});
}
public static IntPtr SetFocusAttached(IntPtr hWnd)
{
var result = new IntPtr();
AttachedThreadInputAction(
() =>
{
result = SetFocus(hWnd);
});
return result;
}