8/12/2006

Single Instance Application, Passing Command Line Arguments


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, 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 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, is 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.

The Full Article
... including code-walkthrough and downloadable sample code can be found at The Code Project

No comments:

adaxas Web Directory