Single Instance Applications in .NET

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Knowing when an application is already open is critical for some applications. Look, an application such as Notepad or Microsoft Word does not have to check for multiple instances, but applications working with data or high-memory intensive applications could benefit from a single instance check. This article will demonstrate two ways to check whether the application is already running.

What Are Single Instance Applications?

A Single Instance application is an application that limits the program to run only one instance at a time. This means that you cannot open the same program twice.

Creating a Single Instance Application

Open Visual Studio and create a Windows Forms application in either C# or VB.NET.

On the form, add two buttons.

Set a reference to System.Management.

Add the next namespaces to your code:

C#

using System;
using System.Threading;
using System.Windows.Forms;

VB.NET

Imports System
Imports System.Threading
Imports System.Windows.Forms

Add the following function to your code:

C#

   private static int CountInstances()
   {

      string[] strAppLoc = System.Reflection.Assembly
         .GetExecutingAssembly().Location.Split
         ("\".ToCharArray());
      string strAppName = strAppLoc[strAppLoc.Length - 1];

      string strProcessQuery = "select name from CIM_Process where
         name = '" + strAppName + "'";

      System.Management.ManagementObjectSearcher searcher = new
         System.Management.ManagementObjectSearcher
         (strProcessQuery);

      int intCountInstances = 0;

      foreach (System.Management.ManagementObject item in
         searcher.Get())
      {

         intCountInstances++;

         if (intCountInstances > 1)

            break;

      }

      return intCountInstances;
   }

VB.NET

   Private Shared Function CountInstances() As Integer

      Dim strAppLoc As String() = System.Reflection.Assembly. _
         GetExecutingAssembly().Location.Split("".ToCharArray())

      Dim strAppName As String = strAppLoc(strAppLoc.Length - 1)


      Dim strProcessQuery As String = "select name from  _
         CIM_Process where name = '" & strAppName & "'"

      Dim searcher As System.Management.ManagementObjectSearcher = _
         New System.Management.ManagementObjectSearcher _
         (strProcessQuery)

      Dim intCountInstances As Integer = 0

      For Each item As System.Management.ManagementObject In _
            searcher.[Get]()

         intCountInstances += 1

         If intCountInstances > 1 Then

            Exit For

         End If

      Next

      Return intCountInstances

   End Function

The CountInstance function makes use of WMI (Windows Method and Instrumentation) to find out if the application is listed in the currently running processes. Insert the call to the function now inside Button1.

C#

   private void button1_Click(object sender, EventArgs e)
   {

      int intInstances = CountInstances();

      if (intInstances <= 1)
      {

         Application.Run(new Form1());

      }
      else
      {

         MessageBox.Show("Another instance of this program is
            already running. Close other instance first", "Already
            running", MessageBoxButtons.OK,
            MessageBoxIcon.Exclamation);
         Application.Exit();

      }

   }

VB.NET

   Private Sub button1_Click(ByVal sender As Object, _
         ByVal e As EventArgs) Handles button1.Click

      Dim intInstances As Integer = CountInstances()

      If intInstances <= 1 Then

         Application.Run(New Form1())

      Else

         MessageBox.Show("Another instance of this program is _
            already running.  Close other instance first", _
            "Already running", MessageBoxButtons.OK, _
            MessageBoxIcon.Exclamation)

         Application.[Exit]()

      End If

   End Sub

When Button1 is clicked, it calls the CheckInstance function to count the number of running instances of your application. If the count is less than 1, the application can run; otherwise, a MessageBox pops up, informing the user that another instance is already open.

Add the code for Button2.

C#

   private void button2_Click(object sender, EventArgs e)
   {

      bool blnInstance;

      Mutex mutex = new Mutex(false, "Local\AppName",
         out blnInstance);

      if (!blnInstance)
      {

         Application.Exit();

      }
   }

VB.NET

   Private Sub button2_Click(ByVal sender As Object, _
         ByVal e As EventArgs)

      Dim blnInstance As Boolean

      Dim mutex As Mutex = New Mutex(False, "LocalAppName", _
         blnInstance)

      If Not blnInstance Then

         Application.[Exit]()

      End If

   End Sub

Inside Button2, I made use of a mutex to disable applications from being launched more than once at a time.

Conclusion

When it is needed, checking if there are more instances of an application should be done properly, without affecting any other process. I hope you have enjoyed today’s article.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read