.NET: How to open a file with an existing instance?

I have an MDI file viewer. That is, my program can open several files in one instance. By the way, my application is not a single instance of the application, so users can open as many instances as they want.

The behavior I want is

When the user double-clicks a file in Windows Explorer, if there is an existing instance of my application, then open the file with that instance else open the file with a new instance. 

I think this behavior is very common. Internet Explorer 9 works like. Therefore, I believe that there must have been many people who have already implemented this before. Is there any well-proven .NET (C #) sample code for this (without using the Win32 API, if possible)?

I assume the algorithm may be something like the following, but I don't know if this is the best or cleanest code to implement it (without using the Win32 API).

 At the program start up 1)If there are arguments in Main(), check for existing instances. 2)If an instance exists, send a message to the instance so that it can open the file. Then exit. 3)else open the file. 

---- Added ----- For those two people who answered my questions with existing answers.

MY STATEMENT IS NOT AN APPLICATION OF SINGLETON! You are welcome. This is the same as Internet Explorer 9. I looked at WCF P2P, since I have to broadcast a message with an open file for every running instance of my application, and then select one of them. But using WCF P2P seems to be a lot for this, because it seems to open and listen on TCP ports. What would be the best practice?

+4
source share
2 answers

Edit: since your application is not single, check the link that Doc Brown pointed out ( Opening a “known file type” in an executable instance of a custom .NET application ), there is a corresponding answer in this link by Joel Martinez.

I will give his answer for quick reference:


How would I do this:

  • First of all, in the main method, check the process list for an existing application instance.
  • If found, send the file name / path to the already running instance using your favorite interprocess communication method ( sending message windows , remote access, wcf, etc.).
  • Close the new process that Windows tried to start (because the existing instance already processed the file with an open operation

I assume that you already know how to make IPC, assuming that you went through WCF P2P, but if not, I will also send a link to this. Although the answer is aimed at a singleton scenario, it will work just fine for you. Just select the last instance by creating a date and time or any criteria suitable for your scenario.

Remember, however, that you cannot pick up the last active instance using this method, without actually tracking it yourself, or by polling this information from your new instance.

Link: System.Diagnostics.Process.GetProcesss

+1
source

All Articles