Introduction
The following code demonstrates how to detect if there is an instance of your
application already running. If detected, it will bring that application to the
foreground (restoring its window state if iconic), and then terminating the current
application. This is useful in instances where you want to ensure that only one
instance of your application is running.
This code was put together using the prior work of Taylor Wood ("Window Hiding in C#") and
a message in the C# forum posted by David Wengier illustrating the use of the
Process class. Without their help, this would have taken me several hours
to put together, instead of a few minutes!
The Code
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
class AppMain
{
[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_HIDE = 0;
private const int SW_SHOWNORMAL = 1;
private const int SW_SHOWMINIMIZED = 2;
private const int SW_SHOWMAXIMIZED = 3;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_RESTORE = 9;
private const int SW_SHOWDEFAULT = 10;
static void Main()
{
string proc=Process.GetCurrentProcess().ProcessName;
Process[] processes=Process.GetProcessesByName(proc);
if (processes.Length > 1)
{
Process p=Process.GetCurrentProcess();
int n=0;
if (processes[0].Id==p.Id)
{
n=1;
}
IntPtr hWnd=processes[n].MainWindowHandle;
if (IsIconic(hWnd))
{
ShowWindowAsync(hWnd, SW_RESTORE);
}
SetForegroundWindow(hWnd);
return;
}
}
}
Conclusion
This code is a great example of interfacing with
Win32 libraries and using some esoteric functions in .NET.