Video tip C#: Ensure only one instance is running






4.65/5 (11 votes)
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#
Copy Code
using System.Diagnostics;
Second, use the process object to get the process name.
C#
Copy Code
// we need to get the current process name string strProcessName = Process.GetCurrentProcess().ProcessName;
Find the process name in the current process collection.
C#
Copy Code
// 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#
Copy Code
// 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.