Activate an existing browser window with a given URL from a C # application (without starting a reboot)

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; // abort search
    }
    else
    {
        return true; // keep on searching
    }
}

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?

+2
source share
1 answer

This will work if the user has this site in their browser. If they use a tabbed browser and the site is open, but not on the selected tab, I do not believe that you will ever find a browser window. (EnumWindows only lists top-level windows).

, , , .

, , , , . GUI , .

+1

All Articles