1

I have a simple .html file defined as below.
If I open it with a normal Web Browser, its background color can be displayed correctly. But when I open it with a System.Windows.Forms.WebBrowser control, the background color can't be displayed.

<head>
  <meta charset="UTF-8">
<style>
nw {
    background-color: Orange;
}
np {
    background-color: DodgerBlue;
}
</style>
</head>
<table style="width:100%">
  <tr>
    <th>Time Created</th>
    <th>Content</th>
  </tr>
  <tr>
    <td>26/11/2018 20:39:21</td>
    <td><nw>hello</nw></td>
  </tr>
 </table>

The Form's TransparencyKey doesn't help; the WebBrowser doesn't have a BackGround color property.

Does anyone know why and how to solve?

Jimi
  • 29,621
  • 8
  • 43
  • 61
York
  • 103
  • 10

1 Answers1

1

In order to modify the aspect of a Html page content, you need to modify the HTML document itself.
The Form's TransparencyKey property and/or the WebBrowser control BackColor property are not relevant. These properties, when available, modify a control's aspect, not the HTML content or its rendering.

Also important: the WebBrowser control, when not otherwise instructed, defaults to IE7 compatibility mode. Many HTML features are not available in this mode.

There are different ways to set/modify the compatibility mode of the WebBrowser class.
You can modify a Registry key to set the IE11/Edge compatibility mode permanently. See this answer:
How can I get the WebBrowser control to show modern contents?

Note that the Key is in the CURRENT_USER branch. You don't need elevated privileges to modify it.
Also, this is not a special hack. This registry value is applied per-executable (you register here your own program), it doesn't modify the general user settings. Notorious programs use this method to set the WebBrowser control compatibility mode.

Another non-permanent, per-document method is to set the HTML header using the HTML5 format:

<!DOCTYPE html>
<meta http-equiv='x-ua-compatible' content='IE=edge'>

Adding these lines to an Html Document, sets the compatibility mode to IE11/Edge.
Your document can be modified as follows:

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv='x-ua-compatible' content='IE=edge'>
  <meta charset="UTF-8">
<style>
nw {
    background-color: Orange;
}
np {
    background-color: DodgerBlue;
}
</style>
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Time Created</th>
    <th>Content</th>
  </tr>
  <tr>
    <td>26/11/2018 20:39:21</td>
    <td><nw>hello</nw></td>
  </tr>
 </table>
</body>
</html>
Jimi
  • 29,621
  • 8
  • 43
  • 61
  • Problem solved by setting the HTML header using the HTML5 format. This solution is better to my case, as the .html file the WebBrowser reads is generate by this application, it is under control (at least till now). – York Dec 01 '18 at 19:26