none
How to get font size of currently selected text in WebBrowser control

    Question

  • Hi,

    is there any way to get the font size of the currently selected text in the Microsoft WebBrowser control (MSHTML)?

    I am aware of

      IHTMLDocument2::queryCommandState("FontSize", ...)

    but this method only returns a value between 1 and 7, for the outdated font sizes "xx-small" to "xx-large". For font sizes like "10pt" or "14px", no useful value is returned.

    Is there a more flexible way to determine the font size?

    Regards
    - Frank

    Monday, August 09, 2010 10:59 AM

Answers

  • Hi Aland,

    I think I found the solution:

    mshtml.IHTMLDocument2 doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
    if (doc != null && doc.selection != null)
    {
      try
      {
        mshtml.IHTMLTxtRange range = doc.selection.createRange() as mshtml.IHTMLTxtRange;
        if (range != null)
        {
          mshtml.IHTMLElement2 elem = range.parentElement() as mshtml.IHTMLElement2;
          txtData.AppendText("Current font size: " + elem.currentStyle.fontSize.ToString() + "\r\n");
        }
      }
      catch (COMException ex)
      {
      }
    }
    

    Many thanks for pointing me in the right direction.

    Regards
    - Frank

    • Marked as answer by fmunkert Thursday, August 12, 2010 9:31 AM
    Thursday, August 12, 2010 9:14 AM

All replies

  • Hi Frank,

    I have two methods to retrieve the font size in C#. Please take a look at the code snippet below:

        private int GetFontSizeDirectly(WebBrowser webBrowser1)
        {
          string fontSizeText = webBrowser1.Document.ActiveElement.GetAttribute("size");
          return int.Parse(fontSizeText);
        }
    
        private int GetFontSizeViaStyle(WebBrowser webBrowser1)
        {
          string fontSizeText = "0";
          string styles = webBrowser1.Document.ActiveElement.Style;
          Regex reg = new Regex(@"^(\w+:\w+;)*fontsize:(?<fontsize>\d+(?:px)?);(\w+:\w+;)*$");
          Match m = reg.Match(styles);
          if (m.Success) fontSizeText = m.Groups["fontsize"].Value;
          return int.Parse(fontSizeText);
        }
    

    We could also get it via javascript.
    To append javascript to a document and invoke it in C#, you could follow the article below:
    http://alandli.spaces.live.com/blog/cns!B5038E2897597982!300.entry?sa=900977846
    The javascript function is following:

    function getFontSize(id) {
      var p = document.getElementById(id);
      return parseInt(p.style.fontsize.replace("px", ""));
    }
    

    Let me know if this helps or not.
    Aland Li

    MSDN Subscriber Support in Forum
    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
    Tuesday, August 10, 2010 5:41 AM
    Moderator
  • Hi Aland,

    is there anything special that I have to do to get the non-Javascript methods to work?

    My sample code is really simple:

    private void Form1_Load(object sender, EventArgs e)
    {
      webBrowser1.Navigate("http://msdn.microsoft.com");
      timer1.Interval = 1000;
      timer1.Tick += new EventHandler(timer1_Tick);
      timer1.Start();
    }
    
    void timer1_Tick(object sender, EventArgs e)
    {
      txtData.Text = "";
      if (webBrowser1.Document != null &&
        webBrowser1.Document.ActiveElement != null)
      {
        txtData.AppendText(webBrowser1.Document.ActiveElement.Style + "\r\n");
        txtData.AppendText(webBrowser1.Document.ActiveElement.GetAttribute("size") + "\r\n");
        txtData.AppendText(webBrowser1.Document.ActiveElement.GetAttribute("font-size") + "\r\n");
      }
      else
      {
        txtData.Text = "???";
      }
    }
    

    But no matter what text I am selecting, "ActiveElement.Style" and "ActiveElement.GetAttribute" always return an empty string.

    I am using Visual Studio 2008 with SP1 and I have Internet Explorer 8 installed.

    - Frank 

     

    Tuesday, August 10, 2010 9:24 AM
  • Hi Frank,

    We need to confirm two things before getting the font size.

    1. The document is loaded. In other words, after a DocumentCompleted event is fired.
    2. One element is actived.

    Could you please provide the tested html?

    Regards,
    Aland Li

    MSDN Subscriber Support in Forum
    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
    Wednesday, August 11, 2010 5:24 AM
    Moderator
  • Hi Aland,

    1. DocumentCompleted is fired in my sample code.

    2. Could you please explain what you mean with "activated"? Is this equivalent to "text is selected" or do you mean "focused"? In my case, only the complete document has the focus; what I want is to get the font size of the selected text, not of the focused text.

    The tested html is the source code of the msdn.microsoft.com web page.

    Regards
    - Frank

    Wednesday, August 11, 2010 7:12 AM
  • Hi Aland,

    I think I found the solution:

    mshtml.IHTMLDocument2 doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
    if (doc != null && doc.selection != null)
    {
      try
      {
        mshtml.IHTMLTxtRange range = doc.selection.createRange() as mshtml.IHTMLTxtRange;
        if (range != null)
        {
          mshtml.IHTMLElement2 elem = range.parentElement() as mshtml.IHTMLElement2;
          txtData.AppendText("Current font size: " + elem.currentStyle.fontSize.ToString() + "\r\n");
        }
      }
      catch (COMException ex)
      {
      }
    }
    

    Many thanks for pointing me in the right direction.

    Regards
    - Frank

    • Marked as answer by fmunkert Thursday, August 12, 2010 9:31 AM
    Thursday, August 12, 2010 9:14 AM
  • Hi Frank,

    My methods have restrictions that the related attributes exist, such as style. I took a look at your first reply and found a workaround: we can convert the original value which is from 1 to 7 to a common font size manually. You can take a look at the document below:

        private int GetFontSize()
        {
          var doc = (IHTMLDocument2)this.webBrowser1.Document.DomDocument;
          object res = doc.queryCommandValue("FontSize");
          if (res is DBNull)
            return 0;
    
          switch (Convert.ToInt32(res))
          {
            case 1:
              return 8;
            case 2:
              return 10;
            case 3:
              return 12;
            case 4:
              return 18;
            case 5:
              return 24;
            case 6:
              return 36;
            case 7:
              return 48;
    
            default:
              return 10;
          }
        }
    

    Let me know if this helps or not.
    Aland Li

    MSDN Subscriber Support in Forum
    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.
    Thursday, August 12, 2010 9:16 AM
    Moderator