08 10th, 2008

If you need that the program was started an only to one copy - can take advantage of such simple and useful class:

public class SingleInstance
{
private bool firstInstance = false;

public bool FirstInstance
{
get { return firstInstance; }
}

public SingleInstance()
{
Mutex mutex=null;
try
{
mutex = Mutex.OpenExisting("ProgramName");
}
catch (WaitHandleCannotBeOpenedException e)
{
firstInstance = true;
}

if (mutex == null)
{
mutex = new Mutex(false, "ProgramName");

GC.KeepAlive(mutex);
}
}
}

Now, we need edit Program.cs like here:

[STAThread]
static void Main()
{
SingleInstance single = new SingleInstance();

if (single.FirstInstance)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}

Now the program will be started only in one copy. A code works on the different versions of Windows - including Vista.