# VBForums CodeBank > CodeBank - C# >  Creating a Single Instance of your Application

## Kasracer

In VB.Net 2005, there is a simple property to accomplish this. Unfortunately, C# has no such property.

Now there are many ways to approach this.

*Using a file to determine if the application is running*
*Pro:* This is very simple. You could simply use a SteamWriter to write something as simple as "true" or "false" to a text file and just parse it on load.
*Con:* What happens if your application crashes? You can enclose the entire app in try and catch statements and change the file in a catch or finally block. But what if that crashes? You'd have to impliment some sort of timeout feature which would inevitably lead to bugs in your application where the program thinks its not running when it is and vice versa.

*Checking the list of processes for your application*
*Pro:* This is one of the most used methods. Basically loading the list of all of the currently running processes and comparing the items in the list to your application's process to count the instances. You can also attempt to get the amount of processes with the name of your application.
*Con:* The problem with retrieving all of the running processes is, it can be quite a lot and it usually hurts an application's startup performance. Also, if you get the processes by name, it can be very inaccurate as I can rename every executable on my machine to "MyApp.exe" and in the process list, if I attempt to launch 20 of them, you'll see 20 "MyApp.exe" instances even though none of them are the same application!

*Creating a singleton design*
*Pro:* This method is outlined on MSDN blogs and works quite well.
*Con:* Requires redesign if you're already working on your application and required more time to get working than adding a simple piece of code at the beginning of your project.

*Where does this leave us? MUTEX!*
*Pro:* A Mutex is a way to share a piece of data amongst threads. With a few lines of code it will accurately let you know if there is more than 1 version of your application running.

VB Code:
bool firstInstance;
System.Threading.Mutex mutex = new System.Threading.Mutex(false, "Local\\MyAppName", out firstInstance);
if (!firstInstance)
{
    Application.Exit();
}

I honestly can't find any cons with this code. It's a good idea to declare the mutex as static outside of your Main() method. We need it during the entire running of the application so it stays accurate. Normally you want to release Mutexes but since we need it throughout our entire application, you don't need to worry about it since it'll get cleaned up when your application exists.

----------


## dee-u

Thanks for the code, I can't check it for now and I have a question. For example my exe's name kasracer and ran an instance of it, then renames the exe to deeu and tries to ran it again, does your code handle such scenarios? 

Thanks!

----------


## Kasracer

> Thanks for the code, I can't check it for now and I have a question. For example my exe's name kasracer and ran an instance of it, then renames the exe to deeu and tries to ran it again, does your code handle such scenarios? 
> 
> Thanks!


Yes it will work correctly if the executables have been renamed. I just tested it to double check and it worked flawlessly  :Smilie:

----------


## dee-u

Thanks, I think I tried to play a similar code sometime ago but was unsuccessful when the exe is renamed...

----------


## pelican

the mutex concept is correct. but i've put the piece of code at the start in my static void main(), it doesnt seems to work. i still able to open multiple instances. and i've declare the mutex variable as static variable.

----------


## Kasracer

> the mutex concept is correct. but i've put the piece of code at the start in my static void main(), it doesnt seems to work. i still able to open multiple instances. and i've declare the mutex variable as static variable.


You have to declare it _outside_ of Main() as a public static variable (as well as the firstInstance boolean). Then assign it in the Main() method and check firstInstance.

----------


## Bongo

Hi 

found this peace of code some time ago.
works perfect for me

in Main 


VB Code:
[STAThread]
        static void Main()
        {
            // pass Versionstext into a  static member called m_sApplicationTitle
            Version ver = new Version(Application.ProductVersion);
            m_sApplicationTitle = String.Format("HoRSt .Net 2006 C#{0:#}.{1:#}.{2:#}.", ver.Major, ver.Minor, ver.Build);
            
            // Check if app is runing already
            if (ClassProcessUtils.ThisProcessIsAlreadyRunning())
            {
                // app is runing therefore set focus on the existing app.
                ClassProcessUtils.SetFocusToPreviousInstance(m_sApplicationTitle);
            }
            else
            {
                // Default by VS2005
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                 Application.Run(new FormMain());
            }
        }

and the following in a new class called ClassProcessUtils


VB Code:
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
 namespace HoRSt2006V3
{
    class ClassProcessUtils
    {
        private static Mutex mutex = null;
         /// Determine if the current process is already running
        public static bool ThisProcessIsAlreadyRunning()
        {
            // Only want to call this method once, at startup.
            Debug.Assert(mutex == null);
             // createdNew needs to be false in .Net 2.0, otherwise, if another instance of
            // this program is running, the Mutex constructor will block, and then throw 
            // an exception if the other instance is shut down.
            bool createdNew = false;
             mutex = new Mutex(false, Application.ProductName, out createdNew);
             Debug.Assert(mutex != null);
             return !createdNew;
        }
         [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
         [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);
         [DllImport("user32.dll")]
        static extern bool IsIconic(IntPtr hWnd);
         [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
         const int SW_RESTORE = 9;
         [DllImport("user32.dll")]
        static extern IntPtr GetLastActivePopup(IntPtr hWnd);
         [DllImport("user32.dll")]
        static extern bool IsWindowEnabled(IntPtr hWnd);
         /// Set focus to the previous instance of the specified program.
        public static void SetFocusToPreviousInstance(string windowCaption)
        {
            // Look for previous instance of this program.
            IntPtr hWnd = FindWindow(null, windowCaption);
             // If a previous instance of this program was found...
            if (hWnd != null)
            {
                // Is it displaying a popup window?
                IntPtr hPopupWnd = GetLastActivePopup(hWnd);
                 // If so, set focus to the popup window. Otherwise set focus
                // to the program's main window.
                if (hPopupWnd != null && IsWindowEnabled(hPopupWnd))
                {
                    hWnd = hPopupWnd;
                }
                 SetForegroundWindow(hWnd);
                 // If program is minimized, restore it.
                if (IsIconic(hWnd))
                {
                    ShowWindow(hWnd, SW_RESTORE);
                }
            }
        }
    }
}

----------


## Kasracer

Bongo, that uses the same technique as I posted, it just puts everything in a class that also declares lots of API functions which I was trying to avoid.

Still, good snippet though  :Big Grin:

----------


## Visionary

tHX for the code.

----------


## nmckenzie0420

Thanks for the code examples!!!

Works like a charm!!!

----------


## Paul M

This will only allow one instance of your application, i use this code for a couple of my programs/services...

Make sure you maker a reference to the System.Management class  :Wink: 


C# Code:
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            int count = CheckForRunningInstances();
             if (count <= 1)
            {
                Application.Run(new Form1());
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Another instance of this program is already running.  Two instances cannot run at the same time", "Already running", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Application.Exit();
            }
         }
        private static int CheckForRunningInstances()
        {
             string[] parts = System.Reflection.Assembly.GetExecutingAssembly().Location.Split("\\".ToCharArray());
            string appName = parts[parts.Length - 1];
             string query = "select name from CIM_Process where name = '" + appName + "'";
             System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);
             int hInstCount = 0;
             foreach (System.Management.ManagementObject item in searcher.Get())
            {
                hInstCount++;
                if (hInstCount > 1) break;
            }
            return hInstCount;
        }

----------


## kleinma

kasracer,

Have you ever looked at any code that does this, but also can send any command line arguments from the second instance that is terminated, to the first instance that was already running?

It would exist in the "app already open, user double clicks file in windows that is associated with said app, about to be terminated instance needs to tell already open instance to handle the file" category.

I will go about figuring it out, as I have a need to do this, however I figured I would ask you first since you have this codebank entry.

In VB 2005, setting the "single instance application" checkbox accomplishes this well, however there is a nasty bug that has to do with that feature and firewall software that I need to try to eliminate. They use .NET remoting to accomplish this in VB 2005, which would not be an option to avoid the bug.

In 2008 you can used named pipe classes to do this, however the project it is for is not moving to a new framework anytime soon.

I have also seen some heavy API-centric methods of doing this that basically date back to VB6 but were ported to .NET before the whole single instance checkbox feature existed, however I was looking for a more managed code way first before I resort to direct calls to the Windows API.

----------


## Kasracer

> Have you ever looked at any code that does this, but also can send any command line arguments from the second instance that is terminated, to the first instance that was already running?
> 
> It would exist in the "app already open, user double clicks file in windows that is associated with said app, about to be terminated instance needs to tell already open instance to handle the file" category.
> 
> I will go about figuring it out, as I have a need to do this, however I figured I would ask you first since you have this codebank entry.


I have not seen any code that can do that. I've looked into it but haven't found an easy way to do so. If you come up with a way or find a way that allows sending of commands to the already opened application without the use of APIs then please share  :Smilie:

----------


## kleinma

Reason I ask, is because there is a bug in the .NET 2.0 framework when using the "single instance application" framework when certain common firewalls are on the system. I have filed a bug with MS about this, and they have confirmed it, but have yet to issue a fix. This is because the framework makes use of remoting to accomplish the single instance application that also can forward command line args from instance to instance. Remoting can be affected by firewalls, even when the remoting is all done locally.

Bill McCarthy did up a nice example after he saw my bug (he was even nice enough to reference me and the bug), using named pipes to accomplish the same objective, however these new classes are in the .NET 3.5 framework and Visual Studio 2008.

I have a need for this in .NET 2.0/VS 2005, as I am not migrating these applications anytime soon because they are commercial release, and I had a hard enough time getting everyone up to speed with .NET 2.0

----------


## Kasracer

> Bill McCarthy did up a nice example after he saw my bug (he was even nice enough to reference me and the bug), using named pipes to accomplish the same objective, however these new classes are in the .NET 3.5 framework and Visual Studio 2008.


Wow, that's a pretty cool way to do this. Thanks for the article!



> I have a need for this in .NET 2.0/VS 2005, as I am not migrating these applications anytime soon because they are commercial release, and I had a hard enough time getting everyone up to speed with .NET 2.0


I hear ya. I am in a similar boat as I need my application be to a single instance but still receive arguments.

The only other option I can think of other than using some Win32 APIs is basically writing a temporary file with the arguments and using something like a FileSystemWatcher to execute those in the single instance application. Unfortunately that creates some extra IO overhead but that's all I can think of for now.

----------

