title: Activate existing browser window with given URL from C# application (without triggering reload)
body: <p>From a C# application I want to activate (brint to front) a site that is already open in the users default browser.  I want to do this in a browser agnostic way.</p>
  
  <p>The difficult part (for me at least) is that I do <strong>not</strong> want the browser to open a new tab and the browser <strong>must not reload</strong> the page if it is already open.</p>
  
  <p>I can open the URI in the default browser with</p>
  
  <pre><code>System.Diagnostics.Process.Start("http://foo.example");
  </code></pre>
  
  <p>But the exact behaviour depends on the users default browser (IE6 seems to reuse the current topmost browser window, Google Chrome will always open a new tab and so on)</p>
  
  <p>Another approach I tried was to enumerate all open Windows and find the one I want based on the window title (making the assumption that most browsers set the window title to the title of the currently open page)</p>
  
  <pre><code>public delegate bool EnumThreadWindowsCallback(int hWnd, int lParam);
  
  [DllImport("user32.dll")]
  static extern bool SetForegroundWindow(IntPtr hWnd);
  
  [DllImport("user32.dll")]
  static extern bool EnumWindows(EnumThreadWindowsCallback callback, IntPtr extraData);
  
  [DllImport("user32.dll")]
  static extern int GetWindowText(int hWnd, StringBuilder text, int count);
  
  private bool FindWindowByRx(int hWnd, int lParam)
  {
      Regex pattern = new Regex("Example Title of Page", RegexOptions.IgnoreCase);
      StringBuilder windowTitle = new StringBuilder(256);
      GetWindowText(hWnd, windowTitle, 255);
  
      if (pattern.IsMatch(windowTitle.ToString()))
      {
          SetForegroundWindow(new IntPtr(hWnd));
          return false; // abort search
      }
      else
      {
          return true; // keep on searching
      }
  }
  </code></pre>
  
  <p>using it with:</p>
  
  <pre><code>EnumWindows(new EnumThreadWindowsCallback(FindWindowByRx), new IntPtr());
  </code></pre>
  
  <p>This does what I need it to do, but feels very brittle and hackish, and is probably slow.</p>
  
  <p>Is there a better, more elegant way?</p>