- The SetForegroundWindow API
// For Windows Mobile, replace user32.dll with coredll.dll
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
<DllImport("user32.dll")> _
Private Shared Function SetForegroundWindow(ByVal hWnd As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As IntPtr) As Long
None.
SetForegroundWindow Win32-API not always works on Windows-7 (vista and above).
See Tips & Tricks for a workaround...
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.
Here is the code:
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);
}
}
For the full article see:
http://www.shloemi.com/2012/09/solved-setforegroundwindow-win32-api-not-always-works/
This is especially useful for test automation to make sure the Application Under Test (AUT) retains focus before manipulating it.
This may be called several times in an automated test script, so it is best to create a method similar to the example below.
public static void Main(string[] args)
{
// test code here...
CheckAutFocus(myProcess.MainWindowHandle);
// more test code...
}
public static void CheckAutFocus(hWnd)
{
if (GetForegroundWindow() != hWnd)
{
SetForegroundWindow(hWnd);
}
}
public static bool BringWindowToTop(string windowName, bool wait)
{
int hWnd = FindWindow(windowName, wait);
if (hWnd != 0)
{
return SetForegroundWindow((IntPtr)hWnd);
}
return false;
}
// THE FOLLOWING METHOD REFERENCES THE FindWindowAPI
public static int FindWindow(string windowName, bool wait)
{
int hWnd = FindWindow(null, windowName);
while (wait && hWnd == 0)
{
System.Threading.Thread.Sleep(500);
hWnd = FindWindow(null, windowName);
}
return hWnd;
}
If the window that you have to set in foreground is a .NET form the best thing is to use native code:
http://jorgearimany.blogspot.com/2010/10/win32-setforegroundwindow-equivalent-in.html
The ManagedWindowsApi project (http://mwinapi.sourceforge.net) provides a static property ManagedWinapi.SystemWindow.ForegroundWindow which can be set.
- SetForegroundWindow on MSDN
Here is an alternative Managed API to FindWindow, The article also describes a way to CloseWindow of another process like notepad, not sure if there is such thing in Win32 API, but at least you can do it in .NET! Here is the article: