Introduction
There are different ways to prevent an application from running more than once. This SingleProcessInstance
class solves the problem with minimal effort for the programmer.
Background
This tip is based on the article "C# Single Instance App With the Ability To Restore From System Tray (Using Mutex)". If the application is minimized and a second instance is started, the main form of the first instance will be shown and the second instance will terminate silently.
Using the Code
To use the class, just modify the Main()
function like this:
static void Main(string[] args)
{
SingleProcessInstance.RunMain(args, (_args) =>
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
});
}
Optionally, you can define what should happen if the application was started a second time:
static void Main(string[] args)
{
SingleProcessInstance.RunMain(args, (_args) =>
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}, () =>
{
SingleProcessInstance.BringMainFormToFront();
MessageBox.Show("this application can only be runned in a single instance");
});
}
History