[C#][WinForm]Prevent same process to be executed more than once at the same time: 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 strModuleName = Process.GetCurrentProcess().MainModule.ModuleName;
string strProcessName = Path.GetFileNameWithoutExtension(strModuleName);
Process[] aryProcess = Process.GetProcessesByName(strProcessName);

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. That means, people can run FindMP3.exe and FindMP3_1.exe at the same time.

You can find other approaches from here.

0 Comments:

Random Posts

Powered by Stuff-a-Blog