2009/11/06

Allowing only one instance: a simple approach

This is a simple and easy way to do it if your requirement is simple. Otherwise you should use Mutex.
using System.Diagnostics;

private void Form1_Load(object sender, EventArgs e)
{
 try
 {
  string moduleName = Process.GetCurrentProcess().MainModule.ModuleName;
  string processName = Path.GetFileNameWithoutExtension(moduleName);
  Process[] aryProcess = Process.GetProcessesByName(processName);

  if (aryProcess.Length > 1)
  {
   MessageBox.Show("This program is running already!");
   this.Close();
  }

  //...
 }
 catch (Exception ex)
 {
  //...
 }
}
Note: This will check the process based on the filename. It will not work if the filename is different. For example, if you make a copy of your program (let's say FindMP3.exe) and rename it to a different name like FindMP3_1.exe. People can run FindMP3.exe and FindMP3_1.exe at the same time. You can fix this by checking the filename at program startup.

You can find other approaches from here.

No comments:

Post a Comment