title: C# SetForegroundWindow not working
body: <p>I have restricted my C# windows application to only allow one instance to be running at a time, using this question <a href="https://stackoverflow.com/questions/184084/how-to-force-c-sharp-net-app-to-run-only-one-instance-in-windows">How to force C# .net app to run only one instance in Windows?</a></p>
  
  <p>It works well and does not allow more than one instance of the application to run at the same time.</p>
  
  <p>The problem is that if the user attempts to open a second instance of the application, I want the currently active one to come to the front.</p>
  
  <p>The question I worked from seems to address this, but it is not working for me. </p>
  
  <p>I think it is because my application is not meeting the criteria to allow the method :<code>SetForegroundWindow</code>
  to work. </p>
  
  <p>My question is, how can I achieve this. My code is below:</p>
  
  <pre><code>using System    ;
  using System.Collections.Generic;
  using System.Windows.Forms;
  using System.Threading;
  using System.Diagnostics;
  using System.Runtime.InteropServices;
  
  namespace RTRFIDListener_Client
  {
      static class Program
      {
          [DllImport("user32.dll")]
          [return: MarshalAs(UnmanagedType.Bool)]
          static extern bool SetForegroundWindow(IntPtr hWnd);
  
          /// &lt;summary&gt;
          /// The main entry point for the application.
          /// &lt;/summary&gt;
          [STAThread]
          static void Main()
          {
              bool createdNew = true;
  
              using (Mutex mutex = new Mutex(true, "RTRFIDListener_Client", out createdNew))
              {
                  if (createdNew)
                  {
                      Application.EnableVisualStyles();
                      Application.SetCompatibleTextRenderingDefault(false);
                      Application.Run(new frm_Main());
                  }
                  else
                  {
                      Process current = Process.GetCurrentProcess();
                      foreach (Process process in Process.GetProcessesByName(current.ProcessName))
                      {
                          if (process.Id != current.Id)
                          {
                              SetForegroundWindow(process.MainWindowHandle);
                              break;
                          }
                      }
                  }
              }
          }
      }
  }
  </code></pre>