Just because we like C# doesn't mean we can't borrow from other .NET languages. I've always had good luck and less complication using VB's single instance methodology in my C# applications. This code would go in your
program.cs file:
public class App : Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase
{
#region Constructors
public App()
{
this.IsSingleInstance = true;
this.EnableVisualStyles = true;
this.ShutdownStyle =
Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses;
}
#endregion Constructors
#region Methods
protected override void OnCreateMainForm()
{
this.MainForm = Program.MainForm;
}
protected override void OnStartupNextInstance(
Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
}
#endregion Methods
}
public static class Program
{
#region Fields
public static string[] CommandLine;
public static Form1 MainForm = new Form1();
public static App myApp = new App();
#endregion Fields
#region Events
#endregion Events
#region Properties
#endregion Properties
#region Methods
[STAThreadAttribute]
static void Main(string[] commandLine)
{
CommandLine = commandLine;
Control.CheckForIllegalCrossThreadCalls = false;
Application.EnableVisualStyles();
try
{
string cmdls = string.Empty;
foreach (var s in commandLine)
{
cmdls += s + "\n";
}
myApp.Run(commandLine);
}
catch (Exception err)
{
Console.WriteLine(err.Message, "Main");
}
}
#endregion Methods
}