Switch to another instance of the same application

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

For example, if I have a one-button application and three instances are currently running. Now if i

  • press the button in the first instance, focus on the second instance
  • press the button in the second instance, focus on the third instance
  • press the button in the third instance, focus on the first instance

How can I do it?

+1
source share
2 answers

if you know the handle to 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 a handle to other instances, for example:

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

you can search for these api calls here in SO for more examples, for example, find this:

How to configure an external window?

+7
source

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

Finally, you can find the Inter-Process Communication (IPC) solution that lets you send messages between processes.

I wrote a simple .Net XDMessaging library that makes this very simple. Using it, you can send instructions from one application to another, and in the latest version even transfer serialized objects. This is a multicast implementation using the 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; } } 
0
source

All Articles