Single instance of C# application

The System.Diagnostics namespace in the .NET Framework provides classes that enable interaction with system processes, event logs, and performance counters. To determine if there are other instances of a C# application running in the system, you can utilize the Process class and its GetProcessesByName method.

using System.Diagnostics;

GetProcessesByName method

Using the GetProcessesByName method, you can create an array of new Process components associated with all the process resources that are running the same executable file on the local computer. This allows you to obtain a list of processes with the same name as your application.

Process[] _process = null; _process = Process.GetProcessesByName (Process.GetCurrentProcess().ProcessName);

Checking the length of the processes array, you can determine if there are other instances of the application running. If the length is greater than 1, it indicates that other instances of the application are running. Otherwise, if the length is 1 or less, it means that no other instances of the application are running.

The above code _process array receiving all the associated processes. If the _process array contains more than one instance , then we should clear the instance already exist.

Full Source C#
using System; using System.Windows.Forms; using System.Diagnostics; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Process[] _process = null; _process = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName); if (_process.Length > 1) { MessageBox.Show("Multiple instancess running..."); } else { MessageBox.Show("Single instance only...."); } } } }

Conclusion

Using the Process class and its GetProcessesByName method, you can programmatically determine the presence of other instances of a C# application running on the local computer. This information can be used to implement specific behavior or provide appropriate messaging within your application.