Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing argument to another instance of the same application

I'm having a seriously problem with my little application; basically it's very easy to understand:

My software, when opened, do it's things.

I want to focus to opening another instance (And I mean opening again the .exe) ,check if it's already opened. If not simply start the application but if it's already running (AKA second or more instance) "simply" pass input argument (the args string array)to the first instance, that will processate it adeguately.

Here's my program.cs

static class Program
{
    static Mutex mutex = new Mutex(true, "{blabla}");

    [STAThread]
    static void Main(String[] args)
    {
        if (mutex.WaitOne(TimeSpan.Zero, true))
        {
            //First Instance!

            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                CALL A MY STATIC METHOD, DO SOME THINGS

                Application.Run(new Form1());
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }
        else
        {
            //Not-so-first instance!
            CALL A STATIC METHOD, 
            DO OTHER THINGS LIKE COMUNICATE WITH FIRST INSTANCE

            SIMPLY CLOSE.
        }
    }
}

This will only recognize (with mutex) if it's already opened but (off course) it can't communicate anything to the main instance.

I've tried lot of things but I can't get it work.

I've tried this but I seriously don't understand (after a lot of time wasted) how to put my "first time" code and the "already running" code.

Tried also MSMQ but I can't make it work.

Can someone please help me? It's a basic software that do a very basic things but I've spent day to make it work like I want!

like image 597
Alex DG Avatar asked Nov 20 '22 05:11

Alex DG


1 Answers

One of the simplest ways to communicate would be to send a Windows message from the second instance to the first instance. The second instance would use PostMessage to send the message and the first instance would override the WndProc method of Form1 to handle the message.

There is an example here: Send message to a Windows process (not its main window)

That question also has an answer that uses a pipe (and WCF) for the communication.

There are many forms of interprocess communication. Which one you use depends on your needs, for example Windows Messages can't carry a great deal of information whereas a pipe can stream data at very high speed.

Update A simple alternative could be IPCChannel . This allows you to create an object in the first instance that can be called by the second instance. You can create a method on that object and pass your data as arguments

like image 63
David J Avatar answered Dec 05 '22 14:12

David J