65.9K
CodeProject is changing. Read more.
Home

Video tip C#: Ensure only one instance is running

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.65/5 (11 votes)

Oct 22, 2011

CPOL
viewsIcon

64751

How to ensure that only 1 instance of the windows application is running

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.
 

C#
using System.Diagnostics;


Second, use the process object to get the process name.

C#
// we need to get the current process name
string strProcessName = Process.GetCurrentProcess().ProcessName;


Find the process name in the current process collection.

C#
// check if this process name is existing in the current running processes
Process[] Oprocesses = Process.GetProcessesByName(strProcessName);


Depending on the process count, make your decision.

C#
// if its existing then exit
if (Oprocesses.Length > 1)
{
MessageBox.Show("The application is already running");
}
else
{
// else let the below code run
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.