Search code examples
c#tabcontroltabindexform-load

Controls lose the index when a PDF file is loaded by form_load event in webBrowser control in C#


I have a tabControl on my form in C# windows application that has two tab pages. I disabled the tabIndex of this tabControl. There is a textBox on the first page of this tabControl and a webBrowser on the second page of this tabControl. I want the textBox has the first index by default when form is loading. And this is working very good. But when I add this command:

webBrowser1.Navigate(Directory.GetCurrentDirectory() + "\\help.pdf");

on the form_load event, the textBox doesn't have the index anymore. What should I do?


Solution

  • The .NET WebBrowser control has two events that may help you:

    • OnNavigating
    • OnDocumentCompleted

    The simplest logic would be to persist whether or not the TextBox was focused prior to navigating and to restore the focus state once navigation has finished.

        private bool _bWasTextBox1Focused = false;
    
        private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
        {
            _bWasTextBox1Focused = textBox1.Focused;
        }
    
        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (_bWasTextBox1Focused) textBox1.Focus();
        }