Click here to Skip to main content
13,143,693 members (30,138 online)
Click here to Skip to main content
Add your own
alternative version


41 bookmarked
Posted 15 Aug 2006

Single Instance Application, Passing Command Line Arguments

, 15 Aug 2006
Rate this:
Please Sign up or sign in to vote.
This article shows how to make sure that only one instance of an application will run, and if a second instance is started, it will call a callback function in the first instance, passing its command line arguments. The solution uses .NET Remoting for the callback.


I wanted to make sure that only one instance of a program is running on my machine, and when a second instance would be started, it would pass its command line arguments to the original instance and then terminate. Thus, the original instance can handle everything else, such as opening a file, bringing itself to the foreground, etc. Also, the solution should not employ outdated techniques such as DDE, and should not use any unmanaged code as I had seen in so many other solutions to this problem.


Part 1: Many solutions I have seen walk through the process list in order to identify a previous instance. Others use Mutex, which I found appealing as it is a lot faster and is completely managed code. This solution uses the full path of the executing assembly as the Mutex name, so it is definitely unique.

Part 2: Other solutions use DDE to communicate with the previous instance. I chose .NET remoting because, again, it is fully managed code and not a Windows legacy, and it also works with console applications, while DDE would require a window.

The whole functionality is encapsulated in a class, written in C# using .NET 2.0. To make this work with .NET 1.1, you would have to change some namespaces, otherwise it is fully compatible.

To demonstrate the principle, I created a simple console application. Of course, you'd need to enhance the class a little for general use. This example has, for instance, a fixed port number, and certainly other flaws for generic usage. But it should only demonstrate the principle.

Using the Code

The class that handles the whole thing is named SingletonController, and it has some static methods that would be used by the calling program (your main program).

// test if this is the first instance and register receiver, if so.
    // OK, this is the first instance, now run whatever you want ...
    // Your application code goes here ...
    // send command line args to running app, then terminate


The test whether this is the first instance, as you can see above, creates a delegate (callback) function. This function will be called whenever a second instance is opened.

The else branch handles the second instance, which will pass its arguments before terminating.

The SingletonController class has a couple of building blocks:

  • it defines a ReceiveDelegate, which will be set to the original instance's callback function
  • the IamFirst() function, which returns true if this is the first instance of your application
  • the CreateInstanceChannel() function, which creates a small remoting listener; this receives the arguments from any subsequent instances
  • the Send() function, which sends all arguments from a second instance to the initial instance before it terminates itself.
public static bool IamFirst()
    string m_UniqueIdentifier;
    string assemblyName = 
    m_UniqueIdentifier = assemblyName.Replace("\\", "_");

    m_Mutex = new Mutex(false, m_UniqueIdentifier);

    if (m_Mutex.WaitOne(1, true))
        //We locked it! We are the first instance!!!
        return true;
        //Not the first instance!!!
        m_Mutex = null;
        return false;

This function creates a Mutex based on the full path name of the executing assembly, then tries to lock it. If successful, it calls CreateInstanceChannel(), which will create a small remoting listener. This listener is later responsible for calling your main program's callback function.

private static void CreateInstanceChannel()
    m_TCPChannel = new TcpChannel(1234);
    ChannelServices.RegisterChannel(m_TCPChannel, false);

This function creates the remoting listener. I hard-coded the port as 1234, this is what you want to put into your configuration file.

public static void Send(string[] s)
    SingletonController ctrl;
    TcpChannel channel = new TcpChannel();
    ChannelServices.RegisterChannel(channel, false);
        ctrl = (SingletonController)Activator.GetObject(
    catch (Exception e)
        Console.WriteLine("Exception: " + e.Message);

This function needs to be called by your main program in case it is the second instance (IamFirst() == false). It will send the arguments supplied to the first instance (the remoting listener), which in turn will call your callback function of the first instance. You will notice that this is the only call to a non-static function (ctrl.Receive()), your own code never needs to instantiate the SingletonController class.

The Receive() function finally calls your callback using the delegate member:

public void Receive(string[] s)
    if (m_Receive != null)

Running the Sample Code

After you compile the sample code, do this:

  • open two command windows.
  • run SingletonApp.exe in one of the windows; it will start saying "Hi: 0, Hi: 1, ..." every second and will terminate after 10 iterations.
  • within 10 seconds after the above application runs, start SingletonApp.exe in a second command window and supply some command line arguments; watch the first window printing out the arguments supplied in the second window.

If you supply more than one argument, you will notice that the "Hi: 0, Hi: 1, ..." loop and the loop that prints the arguments run in separate threads, the "Hi" messages and arguments will be printed in an alternating fashion.

Points of Interest

None, this solution has been put together from different solutions I had found on the net, none of which combined it the way I wanted it to be. So, this is basically nothing new, just a new combination.


No changes (yet).


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Program Manager The Boston Consulting Group
Germany Germany
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralSingle instance but with multiple documents Pin
David9357-Feb-14 18:14
memberDavid9357-Feb-14 18:14 
GeneralRe: Single instance but with multiple documents Pin
David9357-Feb-14 18:15
memberDavid9357-Feb-14 18:15 
SuggestionTerminal Server Solution for Single Instance Application Pin
Oleg Halzov19-Apr-12 23:00
memberOleg Halzov19-Apr-12 23:00 
QuestionGood article, but... Pin
Member 258348814-Oct-11 8:04
memberMember 258348814-Oct-11 8:04 
QuestionLaunching SingletonApp already with args Pin
Ares5323-Aug-11 0:31
memberAres5323-Aug-11 0:31 
GeneralAnother approach without mutexes/remoting Pin
FanatiX31-Oct-08 8:24
memberFanatiX31-Oct-08 8:24 
GeneralRe: Another approach without mutexes/remoting Pin
dan2010here12-Apr-09 18:52
memberdan2010here12-Apr-09 18:52 
QuestionHTTP Channel? Pin
Omid.Q.Rose8-Dec-06 14:23
memberOmid.Q.Rose8-Dec-06 14:23 
QuestionShowing a form within the static method myReceive Pin
neilault7-Nov-06 23:10
memberneilault7-Nov-06 23:10 
GeneralVery good. An addition Pin
Daniel Ruehmer24-Oct-06 22:01
memberDaniel Ruehmer24-Oct-06 22:01 
GeneralIssues when trying to use implement SingletonController.cs Pin
nip908-Oct-06 23:37
membernip908-Oct-06 23:37 
AnswerRe: Issues when trying to use implement SingletonController.cs Pin
Daniel Ruehmer24-Oct-06 21:51
memberDaniel Ruehmer24-Oct-06 21:51 
GeneralNice, but a few suggestions... Pin
mav.northwind15-Aug-06 23:43
membermav.northwind15-Aug-06 23:43 
GeneralRe: Nice, but a few suggestions... Pin
GamerX8725-Jun-07 12:35
memberGamerX8725-Jun-07 12:35 
GeneralDo not use mutexes for this! Pin
Ramon Smits15-Aug-06 21:27
memberRamon Smits15-Aug-06 21:27 
GeneralRe: Do not use mutexes for this! Pin
mav.northwind16-Aug-06 5:38
membermav.northwind16-Aug-06 5:38 
GeneralRe: Do not use mutexes for this! Pin
kian0116-Aug-06 21:07
memberkian0116-Aug-06 21:07 
GeneralRe: Do not use mutexes for this! Pin
Aaron Sulwer12-Sep-06 7:04
memberAaron Sulwer12-Sep-06 7:04 
GeneralRe: Do not use mutexes for this! Pin
Aaron Sulwer11-Sep-06 10:04
memberAaron Sulwer11-Sep-06 10:04 
GeneralRe: Do not use mutexes for this! Pin
Ares5322-Aug-11 6:08
memberAres5322-Aug-11 6:08 
GeneralUse an IPC Channel -- not a tcp channel Pin
Ian MacLean15-Aug-06 17:55
memberIan MacLean15-Aug-06 17:55 
GeneralRe: Use an IPC Channel -- not a tcp channel Pin
kian0116-Aug-06 21:09
memberkian0116-Aug-06 21:09 
GeneralRe: Use an IPC Channel -- not a tcp channel [modified] Pin
Aaron Sulwer11-Sep-06 10:06
memberAaron Sulwer11-Sep-06 10:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170915.1 | Last Updated 15 Aug 2006
Article Copyright 2006 by kian01
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid