This is something I find myself looking up alot so I decided to put it into a post for easy access, and for anyone else who might be looking for a solution.
using System.Threading;
static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "SignleInstance", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } } }
Download Single Instance Application Source Code
I still don’t get why in Visual Studio in VB.NET one could click make single instance application, but that same feature doesn’t exist in C#? Don’t all .NET languages just get compiled to the CIL in the end?
It’s true that both C# and VB.NET compile to MSIL, but I doubt it has anything to do with the languages. Back in the days of VB6, there was a property to easily detect if another instance of your application was running (app.PrevInstance). VB.NET is not a derivative of VB6 and doesn’t support that property. My guess is that providing a VS template was part of Microsoft’s plan to ease the transition for VB6 developers.
Using a mutex is the proper way to handle this and is almost certainly what’s happening under the hood in VB.