SMUsamaShah
SMUsamaShah

Reputation: 7890

Switch to other instance of same application

I want my c# winform application to switch to another running instance if a certain event occurs.

For example if I have a application with just a button and three instances are running at the moment. Now if I

  1. press the button in first instance, focus to second instance
  2. press the button in second instance, focus to third instance
  3. press the button in third instance, focus to first instance

How do i do that?

Upvotes: 1

Views: 1185

Answers (2)

TheCodeKing
TheCodeKing

Reputation: 19230

SetForegroundWindow is a great solution. An alternative is to use named Semaphores to send signals to other applications.

Lastly you could look for a Inter-Process Communication (IPC) solution which would allow you to send messages between processes.

I wrote a simple .Net XDMessaging library that makes this really easy. Using it you can send instructions from one application to other, and in the latest version even pass serilaized objects. It's a multicast implementation that uses a concept of channels.

App1:

IXDBroadcast broadcast = XDBroadcast.CreateBroadcast(
                                       XDTransportMode.WindowsMessaging);
broadcast.SendToChannel("commands", "focus");

App2:

IXDListener listener = XDListener.CreateListener(
                                      XDTransportMode.WindowsMessaging);
listener.MessageReceived+=XDMessageHandler(listener_MessageReceived);
listener.RegisterChannel("commands");

 // process the message
private void listener_MessageReceived(object sender, XDMessageEventArgs e)
{
    // e.DataGram.Message is the message
    // e.DataGram.Channel is the channel name
    switch(e.DataGram.Message)
    {
        case "focus":
        // check requires invoke
            this.focus();
            break;
        case "close"
            this.close();
            break;
    }
}

Upvotes: 0

Davide Piras
Davide Piras

Reputation: 44605

if you know the handle of the other instances you should just call the Windows API: SetForegroundWindow:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

you can use the FindWindow API call to get the handle of the other instances, for example:

 public static int FindWindow(string windowName)
    {
        int hWnd = FindWindow(null, windowName);

        return hWnd;
    }

you can search for those api calls here in SO for more examples, for example found this one:

How do I focus a foreign window?

Upvotes: 7

Related Questions