Is it possible to change the background color of t

2020-02-10 18:03发布

问题:

I have a page that contains a WebBrowser control that is frequently updating content. I am using a black background, but the default color before loading content of the WebBrowser is white. I could change it by loading a small HTML string with the background set to black but there is still a period of time when the WebBrowser appears as white so there is a sort of a flickering effect happening.

My question is this: is there any way to change the color of the underlying control of the WebBrowser?

I have tried a few solutions such as hiding the WebBrowser until the content has been loaded but none of these feel very elegant and don't work all that well.

回答1:

I've figured out something that works in my case. It's not necessarily the most elegant but it gets the job done.

I set the default Opacity of the WebBrowser to 0. Then, I attach an event handler for the LoadCompleted event:

private void browser_Post_LoadCompleted(object sender, NavigationEventArgs e)
{
    browser_Post.Opacity = 1;
}

Now, before I load a new HTML page, I set the Opacity back to 0 so it hides the browser while the new HTML is being rendered so there is no flickering of backgrounds. When the HTML is finished loading the event will fire and the new HTML page will be shown as expected.



回答2:

I agree with johnforrest. Its much better to Set the default Opacity to 0 and Opacity mask to Black in the XAML code. After that in the LoadComplete event;

private void dataBrowser_LoadCompleted(object sender,NavigationEventArgs e)
{
    dataBrowser.OpacityMask = null;
    dataBrowser.Opacity = 1;
}

No flickering...!!



回答3:

Assuming you don't want to change the actual opacity as per the other suggestions, you can change the background colour of the initial display using HTML:

  this.WebBrowser1.Navigate("about:blank");
  IHTMLDocument2 _doc = this.WebBrowser1.Document.DomDocument as IHTMLDocument2;
  _doc.write("<html><body style=\"background: #f0f0f0\"></body></html>");


回答4:

I have found that changing the Opacity or Visibility of the control does not completely hide the flickering. My solution is to set the height of the control to 0 and then reset it back after it loads, like this:

double savedHeight = browser.ActualHeight;
browser.Height = 0;

browser.Navigated += (sender, e) =>
{
    browser.Height = savedHeight;
}

browser.Navigate(...);