简体   繁体   中英

loading a local HTML file into the WebBrowser control keeps causing a loop

I am trying to create my own web browser that opens up a web page I created that is stored locally. I am new to writing in C# and have gotten the browser to work for the most part but I can not get the web page to open. I have tried several different commands and keep getting the same result.This is the command I am using to open the file:

private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    string curDir = Directory.GetCurrentDirectory();
    var url = new Uri(String.Format("file:///{0}/{1}", curDir, "START_HERE.html"));
    webBrowser1.Navigate(url);
}

The browser opens with no problem but the page keeps loading and doesn't stop. I tried moving the code to the webBrowser1_Navigating instead and it opens the web browser but the page comes up blank. The file is set to copy to Output Directory as Content.

I thought it might be the progress bar and tried several different ways of creating it but keep getting the same results.

This is the code for the Progress Bar:

private void webBrowser1_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
    try
    {
        if (e.MaximumProgress != 0)
            ProgressBar1.Value = (int)(((double)e.CurrentProgress * 100) / e.MaximumProgress);
        if (ProgressBar1.Value < 0)
            ProgressBar1.Value = 0;
        else if (ProgressBar1.Value > 100)
            ProgressBar1.Value = 100;    
    }
    catch (Exception ex)
    {           
    }
}

What can I do to fix the loop? I know I'm missing something but not sure what.

Where your post says

private void webBrowser1_Navigated(...)

do you mean "Navigate" instead of "Navigated"? Because if so, you are causing the loop oby calling Navigate inside of Navigate.

You have to go to the properties for the webBroswer control and remove the event handler that is pointed at webBroswer1.Navigated. You probably don't want to have a navigate command in any event handler associated with navigation as you'll probably have unpredictable looping as you're experiencing.

Put your code in the webBrowser1.ControlAdded. This gets called when the form gets built and the web browser is added to it's parent container. It will only get called once and is independent of the navigation process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM