Controlling one instance of the application from another?

  • Thread starter Thread starter melon
  • Start date Start date
M

melon

Let's say I have a program.exe file. When I run it, one instance of
it will be created.

If I run it again, then another instance will be created. Question
is, is it possible for instance #2 to issue command to instance #1, or
vice versa?

Thanks
 
Via some form of IPC (remoting, WCF, a shared file, sockets, etc etc
etc), yes.

The implementation depends on what you need...

Marc
 
There are many-a-ways to achieve that...
1) You can use Mutex
2) At the program constructor, trace the process that are currently running
on the system, take either name or id of the application and compare with the
current.. application.

If you need more details with code, ping me back..

HTH
 
Using the process as below

First create a method to get the instance is already running or not as below

using System.Diagnostics;

public static Process PriorProcess()
{
Process curr = Process.GetCurrentProcess();
Process[] procs = Process.GetProcessesByName(curr.ProcessName);
foreach (Process p in procs)
{
if ((p.Id != curr.Id) &&
(p.MainModule.FileName == curr.MainModule.FileName))
return p;
}
return null;
}

Now by using this, you can check at the Main method as

static void Main() // args are OK here, of course
{
if (PriorProcess() != null)
{
MessageBox("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was here
}

Regarding Mutex usage... if you can do R&D that's great. But if you want me
to post the details here will do that...

HTH and don't forget to rate the post
 
Although "one instance only" is a common request, I'm not sure it is
what the OP asked on this occasion?

Marc
 
Back
Top