Home » Windows OS

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


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?

- Frank


6 Answers Found


Answer 1

Hi Frank,

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

privateint GetFontSizeDirectly(WebBrowser webBrowser1)
      string fontSizeText = webBrowser1.Document.ActiveElement.GetAttribute("size");

    privateint 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;

We could also get it via javascript.
To append javascript to a document and invoke it in C#, you could follow the article below:
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


Answer 2

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:

privatevoid Form1_Load(object sender, EventArgs e)
  timer1.Interval = 1000;
  timer1.Tick += new EventHandler(timer1_Tick);

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");
    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 



Answer 3

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?

Aland Li

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


Answer 4

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.

- Frank


Answer 5

Hi Aland,

I think I found the solution:

mshtml.IHTMLDocument2 doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
if (doc != null && doc.selection != null)
    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.

- Frank


Answer 6

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:

privateint 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;

          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


How to set font size programmatically (VB or C#) in WebBrowser control or zoom WebBrowser control
I use new WEBBrowser control (VS2005) in my program (WinForm) for open web site. (VB2005)
After using method "navigate", in my webbrowser control I have HTML page from some website.
This HTML page  has some input button with events  or input text control or other interactive control on it. I can click with mouse on that buttons or input text from keyboard or select value from combo box to send this page back.
Idea question:
How I can execute this  from my program code, using property and methods WebBrowser control???
Thank for attention.



I'm hosting a webbrowser control and loading a URL that contains a a small form that is embedded in the larger web page content. After the page is loaded, I'm modifying the html/css in memory to deleted various html elements (mostly divs) that surround the embedded form div so that the end result is all you see in the browser is the sub form.

Problem I'm having is that i want to resize the webbrowser control to fix the displayed content so I can then center webbrowser control in the C# form. I can't figure how to do this.

I tried stuff like:

	webBrowser1.Height = webBrowser1.Document.Body.OffsetRectangle.Height;
webBrowser1.Width = webBrowser1.Document.Body.OffsetRectangle.Width;

But the browser continues to display scrollbars. I'm not that far off but enough to cause the scroll bars to appear. I new to working with the webbrowser and don't really understand how the cumulative sizing of all the nested elements works and how these correspond to the browser control size.



I'm writing a couple of custom controls in VB.Net 3.5, in VS2008, and would like to resize the font size based on the height of the control, and vice-versa. Is there any way of converting a font of say 38.25pts into a me.height, or the other way round?

I realise the font width will change dependent on the font used (which isn't an issue for my purposes), but as far as I know, the font height is usually consistent!

Accessibility/Large font settings won't be an issue with this application.

Thanks in advance


We're using Team System 2008, IE8.  When you hover over Font and Font Size, it doesn't highlight like it's enabled.  When you hover over Font Color and Background, it does highlight it, like it'll dropdown, but when you click on it, nothing happens.

Hi there.

I have developed a winforms application using Visual Studio 2008 (written in Visual Basic).  All of my forms and controls were designed (and sized) using the standard MS San Serif 8.25 font.  However, on some users computers, another font (I think Arial) is being used, even though the c:\windows\fonts folder does contain the MS San Serif font.

Worse is the font that is selected requires more space than the MS San Serif font.  This means that labels and button captions are cutoff/wrapped/misaligned which looks horrible (not to mention you cannot read the entire label/caption).

The target machines in one group are all XP SP3.  I cannot figure out why some machines work fine and some not.  On those same computers, reports (designed using Crystal Reports) also have the same problem.  The font the reports were designed with is not used, even though it is on the computer.

Can anyone give me a clue as to why this would happen? 


Is it possible to set the defaul text format in CRM4 email - we have a company Standard for email format etc, including signatures, but CRM defaults to Taloma 10 pitch?  I would have thought this would have been easy to do, but i see no options settings for Font Face, Sizes etc

I have a name badge which needs to fit some really long names. I can't use 'Can Grow', the name needs to be on one line and the width of the text box is limited to the width of the report.

I currently count the number of characters and reduce the font size but this is not accurate.

I don't believe there is a way to measure the physical length of the text or is there?

Or is there a better approach?

<!-- /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} -->

How to change font name and size text printing using dos mode

I am using vb code for printing invoice ,my invoice header field some client company name printed, I want change company name font name and size my invoice header field

Pls send some idea .this is my code

PrintLine(1, Space(13) & "RACE")

PrintLine(1, Space(12) & "============================")

'PrintLine(1, Space(60))

PrintLine(1, Space(12) & "CONTACT - PH:22471987")



I have a map with custom pushpins. The look like the default pushpins but they are smaller (26 x 17). Now the default font is to large. How can I get it smaller. One further question: How can I center the text in the middle of the icon?

My actual code is the following:

var pin = map.AddPushpin(new Microsoft.Maps.Location(" . $v->lat . "," . $v->lon  . "),

{ text: '1', height: '26px', width: '17px' , sticky: true, icon: '/images/icon_green.png' });

Thank you very much in advance.

I searched for several hours to solve the problem by myself, but I didn't find anything. :-(

Regards. Frederik



there is an other similar post http://social.msdn.microsoft.com/Forums/en-US/vsautotest/thread/c1c08a0e-e2f7-4d5f-a0f4-a54ef22b2b0c but it is asking about web controls so I decided to make my own since it is kind of different.

I have some win controls, buttons and labels, and what I want to do is to run a test and verify that the size of the text on the controls is correct.

Is there some way to do this with coded UI tests? using the getProperty() method or something?





I tried to display a simple html in a webbrowser control in wp7, but it does not render the contents in the correct size - it shows up too small. Here is the code I tried:(I have removed unnecessary parts)

<phone:PhoneApplicationPage x:Name="phoneApplicationPage" 

 <phone:WebBrowser x:Name="Browser1" IsScriptEnabled="True" Height="200"></phone:WebBrowser></phone:PhoneApplicationPage>



where testHtml is:

publicconststring testHtml = @"
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<title>300x50 Test</title></head>
<style type=""text/css"">
	width: 300px; 
	height: 50px; 
	background-color: blue;
font-family: Georgia, serif; 
color: white; 
text-align: center; 
font-size: 24px;
<div id=""box""> 
<div class='font'>300x50</div>

Any help is appreciated.




Hi All,

I want to calculate the total data sent/recieved by a webpage in web browser control. Please suggest me the best method to do this.



Whenever I need to edit the font in a textbox, the font name and font size dropdown lists are greyed out.  I have to change the font from the properties window.  Why is that?

Screenshot can be found here:



Why is it that when I am using a Windows Forms designer, and I choose a size for a font it often comes out to a fractional amount with a .25 or .75 after it, but if I type in the size manually, it does not.

For example, if I change the font for a label control to Arial 11 using the dialog (clicking the ... button in the property manager), then the font actually shows up in the designer as Arial 11.25pt

Arial 12 shows up as Arial 12pt

And Arial 16 shows up as Arial 15.75pt.

But if I manually enter the point size by typing it in without going to the font dialog, it comes out to a nice round number with no fractional part.

What's up with the weird fractional parts coming from the Font chooser dialog?



I want my application to have "Segoe UI", 9F as Font under Windows 7

and "Microsoft Sans Serif", 8.25F under Windows XP (since XP doesn't contain Segoe UI by default).

The problem: when I change the font size programmatically in the Form_Load method, all my buttons' heights decrease. Putting

Font theFont = new Font("Segoe OS", 9);
OperatingSystem osInfo = System.Environment.OSVersion;
if (osInfo.Version.Major < 6)
  theFont = new Font("Microsoft Sans Serif", 8.25f);

at the beginning of InitializeComponent() works, however, then the Form can't be displayed in designer mode anymore.

Thanks in advance.

how to make bigger tabpage page headers without changing tabpage or its contents font size. i just need to change tabpage header to make it look bigger with different font. need help please.


Hi all,

I hope someone can help me out with some information on this.
My problem is as follows:

I load some html text into the webbrowser control with this code:

string bodyText = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>Untitled Document</title><body leftmargin=\"0\" rightmargin=\"0\" topmargin=\"0\" bottommargin=\"0\">";

   string container = "<table width=\"240\" border=\"1\">";

   container += "<tr><td>Test</td>";

   container += "</tr></table></body>";

   string completeDoc = bodyText + container;

   webBrowser1.DocumentText = completeDoc;


I can see the table just fine, but the problem is that even though the width of the table is 240px, it takes up the entire width of a 480 x 800 px screen. So somehow the webbrowser is displaying everything twice as large as it should be. Does anyone know if I am doing something wrong or how it can be resolved?

Any suggestions are very much appreciated!


So I'm not trying to edit the value of the textbox... I really don't know what to do here.

This is the part of the HTML that I want to input text into:

<DIV>To</DIV><DIVstyle="WIDTH: 426px; MARGIN-BOTTOM: 1em"id=message-recipients-containerclass=input-text><ULclass=tbl-holder><LIid=anonymous_element_1class=bit-input><INPUTid=anonymous_element_2class=maininputautocomplete="off"maxlength="32"tabindex="1"></LI></UL><INPUTstyle="DISPLAY: none"id=message-recipients><DIVid=message-recipients-autoclass=autocomplete><DIVstyle="DISPLAY: none"class=default>Type the name of your friend</DIV><ULstyle="DISPLAY: none"class=feed></UL></DIV></DIV>

It's a textbox where you enter names you want to send a message to. Now when I add names... it adds HTML code (obviously):

<FORMid=message-compose><DIV>To</DIV><DIVstyle="WIDTH: 426px; MARGIN-BOTTOM: 1em" id=message-recipients-container class=input-text <LI id=anonymous_element_16>="-Beet-"><ULclass=tbl-holder><LIid=bit-0class=bit-box>NAME1
<LIstyle="DISPLAY: none"id=anonymous_element_22class=bit-input><INPUTid=anonymous_element_23class=smallinputautocomplete="off"maxlength="32"tabindex="1"></LI></LI><LIid=bit-1class=bit-box>NAME2
<LIstyle="DISPLAY: none"id=anonymous_element_46class=bit-input><INPUTid=anonymous_element_47class=smallinputautocomplete="off"maxlength="32"tabindex="1"></LI></LI><LIid=anonymous_element_1class=bit-input><INPUTstyle="WIDTH: 72px"id=anonymous_element_2class=maininputautocomplete="off"maxlength="32"tabindex="1"></LI></UL><INPUTstyle="DISPLAY: none"id=message-recipients><DIVid=message-recipients-autoclass=autocomplete><DIVstyle="DISPLAY: none"class=default>Type the name of your friend</DIV><ULstyle="DISPLAY: none; HEIGHT: 48px"class=feed><LIid=anonymous_element_44class=auto-focus><EM>za</EM>mico2</LI><LIid=anonymous_element_45>Zig<EM>za</EM>g3457</LI></UL></DIV></DIV>

So I'm guessing to do this it's kinda like changing the value of a textbox?

WebBrowser1.Document.GetElementById("message-recipients-container").SetAttribute(attributename, "NAME1")

just with a different attribute name?



I'm trying to copy a specific area of text (actually a row from a table) from the webbrowser control into a richtextbox automatically (finds a specific ID in column 1, selects row and copies it into the box). 

However the web page and table is dynamically created using JavaScript at page load time. I've tried pulling innertext from the body and it shows nothing (when checking the variables in the code window at runtime it literally says "Nothing"), the innerhtml shows me the code to generate the table instead. Is there any way I can interact with what I'm actually seeing in the browser control instead of no text at all or the html that creates what I'm seeing?


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure