Click here to Skip to main content
Click here to Skip to main content

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.

Problem

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.

Solution

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.
if(SingletonController.IamFirst(new 
   SingletonController.ReceiveDelegate(myReceive)))
{
    // OK, this is the first instance, now run whatever you want ...
    // Your application code goes here ...
}
else
{
    // send command line args to running app, then terminate
    SingletonController.Send(args);
}

SingletonController.Cleanup();

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 = 
      System.Reflection.Assembly.GetExecutingAssembly().GetName(false).CodeBase;
    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!!!
        CreateInstanceChannel();
        return true;
    }
    else
    {
        //Not the first instance!!!
        m_Mutex.Close();
        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);
    RemotingConfiguration.RegisterWellKnownServiceType(
        Type.GetType("SingletonApp.SingletonController"),
        "SingletonController",
        WellKnownObjectMode.SingleCall);
}

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);
    try
    {
        ctrl = (SingletonController)Activator.GetObject(
                typeof(SingletonController), 
                "tcp://localhost:1234/SingletonController");
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
        throw;
    }
    ctrl.Receive(s);
}

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)
    {
        m_Receive(s);
    }
}

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.

History

No changes (yet).

License

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

Share

About the Author

kian01
Program Manager The Boston Consulting Group
Germany Germany
No Biography provided

Comments and Discussions

 
GeneralSingle instance but with multiple documents PinmemberDavid9357-Feb-14 18:14 
GeneralRe: Single instance but with multiple documents PinmemberDavid9357-Feb-14 18:15 
SuggestionTerminal Server Solution for Single Instance Application PinmemberOleg Halzov19-Apr-12 23:00 
QuestionGood article, but... PinmemberMember 258348814-Oct-11 8:04 
QuestionLaunching SingletonApp already with args PinmemberAres5323-Aug-11 0:31 
GeneralAnother approach without mutexes/remoting PinmemberFanatiX31-Oct-08 8:24 
GeneralRe: Another approach without mutexes/remoting Pinmemberdan2010here12-Apr-09 18:52 
QuestionHTTP Channel? PinmemberOmid.Q.Rose8-Dec-06 14:23 
QuestionShowing a form within the static method myReceive Pinmemberneilault7-Nov-06 23:10 
GeneralVery good. An addition PinmemberDaniel Ruehmer24-Oct-06 22:01 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 15 Aug 2006
Article Copyright 2006 by kian01
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid