Как внедрить CSS в элемент управления WebBrowser? - PullRequest
17 голосов
/ 31 марта 2011

Насколько мне известно, есть способ внедрить JavaScript в DOM.Ниже приведен пример кода, который внедряет javascript с элементом управления webbrowser:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "function sayHello() { alert('hello') }";
head.AppendChild(scriptEl);
webBrowser1.Document.InvokeScript("sayHello");

Есть ли более простой способ ввести css в DOM?

Ответы [ 2 ]

27 голосов
/ 31 марта 2011

Я не пробовал это сам, но поскольку правила стиля CSS можно включить в документ с помощью тега <style>, например:

<html>
<head>
<style type="text/css">
    h1 {color:red}
    p {color:blue}
</style>
</head>

, вы можете попробовать:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
IHTMLStyleSheetElement styleSheet = element.styleSheet;
styleSheet.cssText = @"h1 { color: red }";
head.AppendChild(styleEl);

идти.Вы можете найти больше информации о IHTMLStyleElement здесь .

Редактировать

Кажется, что ответ намного проще, чем я первоначально думал:

  using mshtml;

  IHTMLDocument2 doc = (webBrowser1.Document.DomDocument) as IHTMLDocument2;
  // The first parameter is the url, the second is the index of the added style sheet.
  IHTMLStyleSheet ss = doc.createStyleSheet("", 0);

  // Now that you have the style sheet you have a few options:
  // 1. You can just set the content as text.
  ss.cssText = @"h1 { color: blue; }";
  // 2. You can add/remove style rules.
  int index = ss.addRule("h1", "color: red;");
  ss.removeRule(index);
  // You can even walk over the rules using "ss.rules" and modify them.

Я написал небольшой тестовый проект, чтобы убедиться, что это работает.Я пришел к этому окончательному результату, выполнив поиск в MSDN для IHTMLStyleSheet, и обнаружил эту страницу , эту страницу и эту .

0 голосов
/ 08 декабря 2018

Для меня это было так же просто, как сначала установить мой стиль в DocumentText. Очевидно, что это не лучшие практики, но это работает для простого CSS.

webBrowser1.DocumentText = "<style> " +
                                 "body { " +
                                    "font-family: Algerian; " +
                                  "} " +
                            "</style> "+
                            "<a href='https://www.google.ca'>Test</a>";
...