DCSIMG
C# Activate Previous Application Instance - Asaf Shelly

C# Activate Previous Application Instance

Published Tuesday, March 09, 2010 5:50 PM

Continuing the following post and as an answer to Jasper:

http://blogs.microsoft.co.il/blogs/asafshelly/archive/2010/03/02/c-close-previous-application-instance.aspx

 

The following code will make sure that only one instance is running by exiting if an instance is already running, and activating that instance.

[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd
);

static bool ActivateApplicationAlreadyRunning
()
{
  
string proc = Process.GetCurrentProcess().ProcessName
;
   Process[] processes = Process.GetProcessesByName(proc
);
   if (processes.Length < 2) return (false
);
   foreach (Process process in processes
)
   {
      if (process.Id != Process.GetCurrentProcess().Id
)
      {
         SetForegroundWindow(process.MainWindowHandle
);
         return (true
);
      }
   }
   return false
;
}

 

[STAThread]

static void Main()
{
   if (ActivateApplicationAlreadyRunning()) return;

.....

תגים:,

Comments

# Jasper said on Wednesday, March 10, 2010 10:21 AM

Thank you for your replay.

  I just don't have VS right now - but as far as I remember there's a problem (?) with SetForegroundWindow() function if the program that you want to set on foreground is minimized (or implement some kinda system tray technic to hide itself from taskbar). As I remember if app1 just minimized the SetForegroundWindow() from app2 just do nothing... :(

# AsafShelly said on Wednesday, March 10, 2010 12:26 PM

I thought that it flashes the window on the task bar 3 times.

Looks like you are right.

Try this addition to the code:

private void Form1_Activated(object sender, EventArgs e)

{

  if (FormWindowState.Minimized == WindowState)

  {

     WindowState = FormWindowState.Normal;

  }

}

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: