Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focusing WebBrowser control in a C# application

Tags:

c#

.net

I have a WebBrowser control hosted in a windows Form. The control is used to display hyperlinks which get created at runtime. These links point to some HTML pages and PDF documents.

The problem is that when the form hosting the browser control is loaded, the focus is on the form. When the TAB key is pressed, the focus does not shift to the first hyperlink. However, if I perform a mouse click on the control and then hit the TAB key, the tab focus is now on the first hyper link. I tried using Select() on the WebBrowser control and then I called Focus(), but it doesn't solve the problem.

Any ideas on how to set the tab focus on the first hyperlink at load? Thanks.

Cheers, Harish

like image 759
HIyer Avatar asked Mar 15 '11 13:03

HIyer


1 Answers

I guess it might be because the focus is set before the page is fully loaded. Try this:

private void Go(string url)
{
    webBrowser1.Navigate(url);
    webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.Document.Body.Focus();
}

You could also automatically select the focus on the first link directly by getting the HtmlElement of that first link.

If the above doesn't work, you might want to check other parts of your code to see if anything else is capturing the focus. Try searching for Select, Focus and ActiveControl in your code.

like image 73
Fun Mun Pieng Avatar answered Sep 18 '22 21:09

Fun Mun Pieng