Sunday, November 1, 2009

[.NET] How to bring window upfront

The stuff on this post can be easily integrated with a previous post:
How to Check if App is Already Running.

In order to bring a window upfront you need to mess with win32 API calls - no easy way around (if you know any please give me a shout). Here's how to import the calls we'll be using:
//Win32 API calls to raise a given processs main window
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);

private const int SW_RESTORE = 9;
Here's a static method to bring a Window upfront in a given winApp (can be easily integrated with the previous post linked above):
static class Program
{

// all the rest of the stuff ... Main other methods etc.

public static void BringOnFront()
{
Process myProcess = Process.GetCurrentProcess();

string myAsseblyName = Assembly.GetExecutingAssembly().GetName().Name;

foreach (Process processId in Process.GetProcessesByName(myAsseblyName))
{
if (myProcess.Id != processId.Id)
{
IntPtr hWnd = processId.MainWindowHandle;

if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}

SetForegroundWindow(hWnd);

break;
}
}
}


}
That'd be all - knock yourself out (tested on a number of XP and Vista machines).

1 comment:

sakthideveloper said...

-right click on the Form and choose properties.
-in the property set the property TopMost=true