In the C # application, I want to activate (on the front panel) a site that is already open in the default browser for users. I want to do this in browser agnostic mode.
The hard part (at least for me) is that I do not want the browser to open a new tab, and the browser should 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 behavior depends on the default browser for users (IE6 seems to reuse the current topmost browser window, Google Chrome will always open a new tab, etc.)
Another approach I tried was to list all open Windows and find the one I want based on the window title (assuming most browsers set the window title to the title of the 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;
}
else
{
return true;
}
}
through:
EnumWindows(new EnumThreadWindowsCallback(FindWindowByRx), new IntPtr());
It does what I need for this, but it feels very fragile and hacky, and probably slow.
Is there a better, more elegant way?