C# Programming > Windows Forms

Single-Instance C# Applications

Single-Instancing

An application that runs only as a single-instance is one that cannot be run more than once at the same time. Certain types of C# applications, especially those that are middle-tier and up can benefit from single-instance behavior.

To achieve single-instance behavior in C# programs, the program must check all the current running processes at load time to make sure it is the only instance running.

.NET Namespaces

Only one additionally .NET namespace is required:

using System.Diagnostics;

That gives you the ability to work with the Process class, which lets C# programmers access useful properties of running processes.

Comparing Processes

The task at hand is to compare the running Windows applications to our C# program. In this case, we are going to compare the application title, since the Process class has the MainWindowTitle property.

So here is a quick stand-alone C# function to check if our application is already running:

private bool IsSingleInstance()
{
     foreach (Process process in Process.GetProcesses())
     {
          if (process.MainWindowTitle == this.Text)
               return false;
     }
     return true;
}

Conclusion

To achieve the full effect, have a C# program check during the Load event if it's a single-instance. Otherwise have the program close itself.

The IsSingleInstance function is rather simple, and of course you can build upon it to write a more complex matching function.

Back to C# Article List