1

Suppose we have a text editor application that runs with one separate process per form. The application is single document (i.e. no tabs or MDI).

We have three forms open with three documents, A.txt, B.txt and C.txt. Now the user double clicks the B.txt file on his desktop. This starts a new instance of the application in question. This launched instance of the editor should now exit and focus/bring to front the already running process that has this file loaded, so that the user does not end up withe same document loaded in two separate forms.

How can I achieve this most easily? In other words, how can I find which process is already showing a document?

The files are not held open by the application once opened, so I can't rely on enumerating the file handles of processes to find the process. I presume this requires some form of communication between the processes. Ideally I'm looking for a .NET solution, but the question is really windows related/language-agnostic.

EDIT: I should mention that for various reasons I'm trying to use separate processes instead of running all forms in a single process.

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77

2 Answers2

1

A good way to solve this problem is using a Mutex: Run single instance of an application using Mutex

You can open a mutex with the current application name + the file name (or something) and then switch to that process when it's already open.

A second solution is using WCF with a pipe binding. Call some kind of "activate" method on a service to have the application activate itself. This link provides some ways of doing interprocess communication.

Community
  • 1
  • 1
Bas
  • 26,772
  • 8
  • 53
  • 86
  • 1
    I should have stated that the first requirement is to run several processes rather than merge to a single instance. I'll add that to the question. I have looked at WCF but without a central hub for the communications it quickly becomes a complicated p2p system just to be able to associate a simple path with a process. I'm thinking there has to be a simpler way (for example the form titles are available from the process objects themselves, they are trivial to get) – Anders Forsgren May 07 '12 at 09:01
1

I'll post the solution used: When a document is opened by an instance of the application, I dump a .pid/.lock file next to the document, containing the pid of the process. This way I can switch to the process having the document open, or clear the lock if that process no longer exists.

Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77