I have restricted my C# windows application to only allow one instance to be running at a time, using this question How to force C# .net app to run only one instance in Wind
Spinning your own single-instance app is generally a mistake, the .NET Framework already supports it strongly and it is rock-solid, very hard to exploit. And has the feature you are looking for, a StartupNextInstance event that fires when the user starts your app again. Add a reference to Microsoft.VisualBasic and make your Program.cs file look like this:
using System;
using System.Windows.Forms;
using Microsoft.VisualBasic.ApplicationServices;
namespace WhatEverYouUse {
class Program : WindowsFormsApplicationBase {
[STAThread]
static void Main(string[] args) {
Application.SetCompatibleTextRenderingDefault(false);
new Program().Start(args);
}
void Start(string[] args) {
this.EnableVisualStyles = true;
this.IsSingleInstance = true;
this.MainForm = new Form1();
this.Run(args);
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs) {
eventArgs.BringToForeground = true;
base.OnStartupNextInstance(eventArgs);
}
}
}
If you have any use for the command line arguments that were used to start the 2nd instance, typical when you use a file association for example, then use eventArgs.CommandLine in your event handler.
try this...
System.Threading.Tasks.Task.Factory.StartNew(() => { SetForegroundWindow(this.Handle); });