2016-12-02 52 views
-1

使用網頁瀏覽器控件。我想要統計瀏覽器中的字符數量,就像Textbox類的textchange一樣。我只想計算顯示文本中字符的數量WebBrowser無html,沒有圖像等關於如何模擬顯示更改文本時觸發的文本框行爲的任何想法?謝謝如何統計瀏覽器控件C#中的字符數?

我在C#中開發Winforms。沒有ASP.NET。

+1

WebBrowser控件顯示一個很多比文字更。例如,它包含圖像。你只想計算它顯示的文本中的字符數量?或者你想計算其源HTML中的字符數?您還暗示TextBox的TextChanged事件,當文本框中顯示的文本發生變化時觸發TextBox ... WebBrowser的等效事件就像Navigated一樣。你的問題需要更多的細節。 –

+0

你在說計數html文件的字符嗎? –

+0

請澄清你的意圖,以便我們可以回答你的問題。 –

回答

1

添加以下類:

using System.Text.RegularExpressions; 

命名空間CK.TicketSystem.Shared { 公共靜態類HtmlUtils { 公共靜態布爾IsHtmlFragment(字符串值){ 返回 Regex.IsMatch(值, @ 「」); }

/// <summary> 
    /// Remove tags from a html string 
    /// </summary> 
    /// <param name="value"></param> 
    /// <returns></returns> 
    public static string RemoveTags(string value) 
    { 
     if (value != null) 
     { 
      value = CleanHtmlComments(value); 
      value = CleanHtmlBehaviour(value); 
      value = Regex.Replace(value, @"</[^>]+?>", " "); 
      value = Regex.Replace(value, @"<[^>]+?>", ""); 
      value = value.Trim(); 
     } 
     return value; 
    } 

    /// <summary> 
    /// Clean script and styles html tags and content 
    /// </summary> 
    /// <returns></returns> 
    public static string CleanHtmlBehaviour(string value) 
    { 
     value = Regex.Replace(value, "(<style.+?</style>)|(<script.+?</script>)", "", RegexOptions.IgnoreCase | RegexOptions.Singleline); 

     return value; 
    } 

    /// <summary> 
    /// Replace the html commens (also html ifs of msword). 
    /// </summary> 
    public static string CleanHtmlComments(string value) 
    { 
     //Remove disallowed html tags. 
     value = Regex.Replace(value, "<!--.+?-->", "", RegexOptions.IgnoreCase | RegexOptions.Singleline); 

     return value; 
    } 

    /// <summary> 
    /// Adds rel=nofollow to html anchors 
    /// </summary> 
    public static string HtmlLinkAddNoFollow(string value) 
    { 
     return Regex.Replace(value, "<a[^>]+href=\"?'?(?!#[\\w-]+)([^'\">]+)\"?'?[^>]*>(.*?)</a>", "<a href=\"$1\" rel=\"nofollow\" target=\"_blank\">$2</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled); 
    } 
} 

}

我必須說,我發現這個班的一些很好的開發者的博客,但不幸的是我不記得在那裏我沒有找到它。

然後你做:

var str = HtmlUtils.RemoveTags(yourHtmlString); 
var numberOfCharacters = str.Length; 

希望它可以幫助

+0

完美。謝謝! –