In .NET, what is the most reliable way to detect if an instance of the same program is already running? Further, what is the best way to pass command line arguments to the already-running instance (e.g. to open a specific document)?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There appears to be three well-known ways of implementing single-instance applications in .NET programs: the process method, the Mutex method, and the Visual Basic method.
Michael Covington discusses the first two in his hint, Ensuring that only a single instance of a .NET application is running.
There’s a CodeProject article that discusses the Mutex method in more detail, including getting the window handle of the existing application so that you can then (somehow) communicate with it.
Another CodeProject article describes how to use classes in the Microsoft.VisualBasic namespace (which is accessible from C#) to implement a single-instance application.
I’m not at all familiar with the third method. Of the first two, they both work but as is pointed out in the linked articles, the Mutex method seems more robust. I don’t know why Mutex was selected as the named object to use. Any of the named synchronization objects (EventWaitHandle, Mutex, Semaphore, etc.) would work.
Communicating with the existing application presents more of a problem. I’d suggest you look into using named pipes, if all you need to do is send a relatively small message to the running application. Check out System.IO.Pipes.NamedPipeClientStream for more information.
I should also note that if you’re worried about security, you’ll need to secure whatever communications method you use. Any application that has sufficient permissions will be able to send information to your running application through the named pipe.