如何在WebBrowser控件中注入CSS

时间:2019-05-13 12:47:50

标签: c# css winforms

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigate("https://www.aparat.com/aleffamily/live2");
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;

    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

        HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
        IHTMLStyleElement element = (IHTMLStyleElement)styleEl.DomElement;
        IHTMLStyleSheetElement styleSheet = element.styleSheet;
        styleSheet.cssText = @"body {background-color:transparent !important; margin: 0px auto; overflow: hidden; }.live__content{display:none;}.chat__footer{display:none;}.chat__header{display:none}#header{display:none}.in-chat-avatar{display:none}.message__username{font-style:italic;font-weight: 800!important;color:ff8f0f !important}.message__text{font-style:italic;font-weight: 400!important;color:ff8f0f !important}.chat__content{ background-color:transparent  !important}.chat{ background-color:transparent  !important}";
        head.AppendChild(styleEl);

    }


}

}

此代码不适用于我,并且出现此错误

  

错误1类型或名称空间名称'IHTMLStyleSheetElement'可能   找不到(您是否缺少using指令或程序集   参考?)C:\ Users \ aleffamily \ documents \ visual studio   2010 \ Projects \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Form1.cs   30 13 WindowsFormsApplication1

1 个答案:

答案 0 :(得分:0)

您尝试使用IHTMLStyleElementIHTMLStyleSheetElement引用什么?它不在.NET框架中的任何地方。

只需修改您的代码以写入通用HtmlElement类型的内容,而不是在样式表中写入.InnerText.InnerHtml的内容

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        webBrowser1.Navigate("https://www.aparat.com/aleffamily/live2");
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {

        HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
        HtmlElement styleEl = webBrowser1.Document.CreateElement("style");
        styleEl.InnerHtml = @"body {background-color:transparent !important; margin: 0px auto; overflow: hidden; }.live__content{display:none;}.chat__footer{display:none;}.chat__header{display:none}#header{display:none}.in-chat-avatar{display:none}.message__username{font-style:italic;font-weight: 800!important;color:ff8f0f !important}.message__text{font-style:italic;font-weight: 400!important;color:ff8f0f !important}.chat__content{ background-color:transparent  !important}.chat{ background-color:transparent  !important}";
        head.AppendChild(styleEl);

    }
}