C# Activate Previous Application Instance
Continuing the following post and as an answer to Jasper:
http://blogs.microsoft.co.il/blogs/asafshelly/archive/2010/03/02/c-close-previous-application-instance.aspx
The following code will make sure that only one instance is running by exiting if an instance is already running, and activating that instance.
[
DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
static bool ActivateApplicationAlreadyRunning()
{
string proc = Process.GetCurrentProcess().ProcessName;
Process[] processes = Process.GetProcessesByName(proc);
if (processes.Length < 2) return (false);
foreach (Process process in processes)
{
if (process.Id != Process.GetCurrentProcess().Id)
{
SetForegroundWindow(process.MainWindowHandle);
return (true);
}
}
return false;
}
[STAThread]
static void Main()
{
if (ActivateApplicationAlreadyRunning()) return;
.....