In this trick, we will try to understand how we can ensure that only one instance of a C# program is running on a computer. I have also created a simple video for the trick below. So you can either see the video or read the below textual description.
http://www.youtube.com/watch?v=8pjfPNfQP2Q[^]
First, import the system.diagnostic
namespace.
using System.Diagnostics;
Second, use the process object to get the process name.
string strProcessName = Process.GetCurrentProcess().ProcessName;
Find the process name in the current process collection.
Process[] Oprocesses = Process.GetProcessesByName(strProcessName);
Depending on the process count, make your decision.
if (Oprocesses.Length > 1)
{
MessageBox.Show("The application is already running");
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
For Further reading do watch the below interview preparation videos and step by step video series.