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.
The difficult part (for me at least) is that I do not want the browser to open a new tab and the browser must not reload the page if it is already open.
I can open the URI in the default browser with
System.Diagnostics.Process.Start("http://foo.example");
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)
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)
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
}
}
using it with:
EnumWindows(new EnumThreadWindowsCallback(FindWindowByRx), new IntPtr());
This does what I need it to do, but feels very brittle and hackish, and is probably slow.
Is there a better, more elegant way?