Click here to Skip to main content
15,883,901 members
Articles / Programming Languages / C#
Article

Single Instance Application, Passing Command Line Arguments

Rate me:
Please Sign up or sign in to vote.
4.48/5 (12 votes)
15 Aug 20064 min read 126.2K   1.9K   43   25
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).

C#
// 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.
C#
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.

C#
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.

C#
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:

C#
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



Comments and Discussions

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