Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WebBrowser control not applying css

I have a project that I am working on in VS2005. I have added a WebBrowser control. I add a basic empty page to the control

private const string _basicHtmlForm = "<html> "
                                      + "<head> "
                                      + "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> "
                                      + "<title>Test document</title> "
                                      + "<script type='text/javascript'> "
                                      + "function ShowAlert(message) { "
                                      + "   alert(message); "
                                      + "} "
                                      + "</script> "
                                      + "</head> "
                                      + "<body><div id='mainDiv'> "
                                      + "</div></body> "
                                      + "</html> ";

private string _defaultFont = "font-family: Arial; font-size:10pt;";

private void LoadWebForm()
{
    try 
    {
        _webBrowser.DocumentText = _basicHtmlForm;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}  

and then add various elements via the dom (using _webBrowser.Document.CreateElement). I am also loading a css file:

private void AddStyles()
{
    try
    {
        mshtml.HTMLDocument currentDocument = (mshtml.HTMLDocument) _webBrowser.Document.DomDocument;
        mshtml.IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet("", 0);

        TextReader reader = new StreamReader(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),"basic.css"));
        string style = reader.ReadToEnd();
        styleSheet.cssText = style;
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Here is the css page contents:

body {
    background-color: #DDDDDD;
}

.categoryDiv {
    background-color: #999999;
}

.categoryTable {
    width:599px; background-color:#BBBBBB;
}

#mainDiv {
    overflow:auto; width:600px;
}

The style page is loading successfully, but the only elements on the page that are being affected are the ones that are initially in the page (body and mainDiv). I have also tried including the css in a element in the header section, but it still only affects the elements that are there when the page is created.

So my question is, does anyone have any idea on why the css is not being applied to elements that are created after the page is loaded? I have also tried no applying the css until after all of my elements are added, but the results don't change.

like image 865
JamesL Avatar asked Apr 01 '10 17:04

JamesL


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 Answers

I made a slight modification to your AddStyles() method and it works for me. Where are you calling it from? I called it from "_webBrowser_DocumentCompleted".

I have to point out that I am calling AddStyles after I modify the DOM.

private void AddStyles()
{
    try
    {
        if (_webBrowser.Document != null)
        {
            IHTMLDocument2 currentDocument = (IHTMLDocument2)_webBrowser.Document.DomDocument;

            int length = currentDocument.styleSheets.length;
            IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet(@"", length + 1);
            //length = currentDocument.styleSheets.length;
            //styleSheet.addRule("body", "background-color:blue");
            TextReader reader = new StreamReader(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "basic.css"));
            string style = reader.ReadToEnd();
            styleSheet.cssText = style;

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Here is my DocumentCompleted handler (I added some styles to basic.css for testing):

private void _webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
  HtmlElement element = _webBrowser.Document.CreateElement("p");
  element.InnerText = "Hello World1";
  _webBrowser.Document.Body.AppendChild(element);

  HtmlElement divTag = _webBrowser.Document.CreateElement("div");
  divTag.SetAttribute("class", "categoryDiv");
  divTag.InnerHtml = "<p>Hello World2</p>";
  _webBrowser.Document.Body.AppendChild(divTag);


  HtmlElement divTag2 = _webBrowser.Document.CreateElement("div");
  divTag2.SetAttribute("id", "mainDiv2");
  divTag2.InnerHtml = "<p>Hello World3</p>";
  _webBrowser.Document.Body.AppendChild(divTag2);

  AddStyles();
}

This is what I get (modified the style to make it as ugly as a single human being can hope to make it :D ):

alt text

like image 173
Andre Artus Avatar answered Sep 28 '22 13:09

Andre Artus


one solution is to inspect the html prior to setting the DocumentText and inject CSS on the client side. I don't set the control url property but rather get the HTML via WebCLient and then set the DocumentText. maybe setting DocumentText (or in your case Document) after you manipulate the DOM could get it to re-render properly

private const string CSS_960 = @"960.css";
private const string SCRIPT_FMT = @"<style TYPE=""text/css"">{0}</style>";
private const string HEADER_END = @"</head>";


 public void SetDocumentText(string value)
{
    this.Url = null;  // can't have both URL and DocText
    this.Navigate("About:blank");
    string css = null;
    string html = value;

    // check for known CSS file links and inject the resourced versions
    if(html.Contains(CSS_960))
    {
      css = GetEmbeddedResourceString(CSS_960);
      html = html.Insert(html.IndexOf(HEADER_END), string.Format(SCRIPT_FMT,css));
    }

    if (Document != null) { 
      Document.Write(string.Empty);
    }
    DocumentText = html;
}
like image 42
MarkDav.is Avatar answered Sep 28 '22 14:09

MarkDav.is