[ACCEPTED]-How to inject CSS in WebBrowser control?-webbrowser-control
I didn't try this myself but since CSS style 9 rules can be included in a document using 8 the <style>
tag as in:
<html>
<head>
<style type="text/css">
h1 {color:red}
p {color:blue}
</style>
</head>
you could try giving:
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);
a go. You 7 can find more info on the IHTMLStyleElement 6 here.
Edit
It seems the answer is much much simpler 5 than I originally thought:
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.
I wrote a small 4 test project to verify that this works. I 3 arrived at this final result by doing a 2 search on MSDN for IHTMLStyleSheet, upon 1 which I happened across this page, this page and this one.
For me it seemed to be as simple as setting 2 my style first in the DocumentText.
Obviously not best 1 practices but it works for simple CSS.
webBrowser1.DocumentText = "<style> " +
"body { " +
"font-family: Algerian; " +
"} " +
"</style> "+
"<a href='https://www.google.ca'>Test</a>";
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.