Click here to Skip to main content
12,951,971 members (57,747 online)
Click here to Skip to main content
Add your own
alternative version


29 bookmarked
Posted 3 Mar 2009

HTMLLabel - An HTML Label for the .NET CF

, 3 Mar 2009 CDDL
Rate this:
Please Sign up or sign in to vote.
A simple HTML Label, with knowledge of some basic HTML.



If you are at least an intermediate level programmer and don’t have time to read the whole article, or you just don’t want to, then the section Using the Code is the place to start.

HTMLLabel is (wouldn’t you say :)) simply an HTML aware Label for the .NET CF 2.0. The last word (CF) is of the most importance, because there are quite a lot of different HTML aware Labels for Windows programmers, but as far as I know, at this moment (the beginning of 2009), there are no freely available HTML Labels for .NET CF, or as you may say, for .NET mobile development. I emphasize the word free, or even better, publicly available, because you can buy some commercially available HTML Labels.

More about this in the rest of the article; let us examine what HTMLabel is capable of:

  1. It can, of course, show some simple HTML code. By simple HTML code, I mean these tags: <b>, <i>, <u>, <pre>, <br>, <font>, and <p>. Besides that, it also uses the <label> tag, but it has a somewhat special meaning and not the classical HTML meaning.
  2. It can replace a lot of different Label objects and combine them together.
  3. It can (as a matter of fact, it does) speed up the InitializeComponent() function. That is quite important in mobile development!
  4. It has a Click event (missing in the Label class in .NET CF).
  5. And also some other nice features...


I am a software developer in one of the largest retailers in our country (a beautiful and quite small country – Slovenia). My job is setting standards for software development throughout our company. We have a lot of different development platforms, and I personally manage different groups of programmers in the C++/Pervasive environment, .NET Mobile environment, Excel/Word VBA environments, VBScript, and Python. As you can see, code manageability is my first and most important task.

For years now, we have used the Oracle Form 3.0 terminal application on our mobile scanners, but last year, we moved to Oracle Forms 10, and this has become too much for old Symbol scanners (OK, let us face it – F10s are too much even for totally new and shaped up scanners!). So we decided to write .NET applications which talk to servers through Web Services... And yes, I have accepted the task to build up a team of coworkers and set up some standards. Quite a big task for a totally C++ guy with no C# knowledge.

Sorry about the big introduction, but: “Hey; that is the background!”.

As I said earlier, we are retailers, so a typical screen in our application looks like this (of course, that is a little bit of a simplification, but it will serve the purpose):

Because we have different scanners which have different screen resolutions and screen sizes, we use different font sizes, so the screen can change at runtime (based on the type of scanner that the application runs on). A screen like that is built up as four panels (all set with Dock=Top), a few Labels, and a few TextBoxes (all set differently so they can rearrange themselves if the font size changes). And, my god, a few applications like that (each with a few screens like that) is a real nightmare to manage!

Wouldn’t it be better if I could use only one object with all the text in it and rearrange textboxes according to the text? And all that would be done at runtime without any need to set the dockings of several objects. Remember, any programmer can change his (or her) code and rearrange screens, but what if you have to do that and it was not your program in the first place? Rearranging all those dockings and calculating the font changes can blow the code sky high.

Yes, this is what HTMLLabel can solve. I know, I know, you expected to find a Label object which can show different fonts, different colors, sizes, and stuff like that, and yes - you have found such a Label – but that is boring; it is just something that you would expect from any HTML aware Label!

Using the code

Very important information

This HTMLLabel object is written for the mobile environment and is not appropriate for Windows programming. This is because the rendering on a mobile device is different from that in a Windows environment. Technically, in .NET CF, you are very limited in GUI functions so you have only one function which can calculate the text size: MeasureString(). And, this is a very inaccurate function, but it is OK on mobile devices.

The same is true for the demo project. You can run the demo project on a PC, but you will probably be disappointed. It is better to use the demo project on a real mobile device or an emulator.

Quick introduction

Using the code is easy:

  1. Download the source code and add the files HTMLParser.cs and HTMLLabel.cs into your mobile project.
  2. Compile the code so Visual Studio can create the HTMLLabel object on the tool bar.
  3. Place the HTMLLabel object from the tool bar on a form.
  4. Change its Text property to some HTML text and you are done.

HTML tags you can use

  • <b> for bold text.
  • <i> for italics text.
  • <u> for underline text.
  • <p> for paragraph .
    • align attribute with values (left, right, center).
  • <font> for changing font.
    • name attribute for font name.
    • size attribute for font size (font sizes are in points, so size=10 means 10 points).
    • color attribute. The color can be any HTML named color (, or a hexadecimal representation of a color in the form of #RRGGBB.
  • <pre> means non-breaking text.
  • <br> means text break.

HTML examples

HTMLLabel1.Text = @"<font size='8' name='Tahoma' color='red'>Tahoma, 8, red</font>";
HTMLLabel1.Text = @"<p align='left'>left</p><p align='center'>" + 
                  @"center</p><p align='right'>right</p>"

Using a special <label> tag

In drawing HTML text on the screen, there are three essential steps:

  1. parsing the HTML text
  2. calculating text positioning based on font and alignment
  3. drawing the text on the surface

The third step is obviously obligatory, but what about the first two? It turns out that the first two steps are the most time consuming (at least on the average mobile devices I am using). So, wouldn’t it be perfect if we could jump over the first two steps? If I change the text, then the first step is obviously obligatory, so is the second and the third. But, what if only change some portion of the text? Well, even then, it is necessary to repeat the first two steps because the change in text can reflect on the whole image.

But, there is an exception to that rule, and in my line of business, this exception is not really an exception, but the rule itself. We have screens with a lot of fixed text, and some parts with changing text, which can occupy part of the screen. The solution I used is, in a special <label> tag which is a label of arbitrary size in the middle of the HTML text. Such HTML text is parsed only once, and also, all the calculations are done only once. After that, the programmer only changes the label value and the text of that label is written to the correct place in the HTML text.

This is how it all looks like:

// First the programmer set the initial HTML text
htmlLabel1.Text = "Desc: <label id='desc' width='100'>"

// ...
// Somewhere in the rest of the code he (she) set the value of the label:
htmlLabel1.ChangeLabelText("desc", "Description X");

The Label tag can have four attributes (the font used for the label is, of course, determined by the font tag used prior to the label tag, or if there is no font tag, the font used for the HTMLLabel itself):

  • id is the most important, because it is the ID by which this label is seen in the code by the programmer.
  • value is the initial value of the label.
  • width is the width of the label on the screen. If it is not specified, it is calculated from the initial text. If the initial text is also not specified, then it is the width of one single space.
  • height is the height of the label on the screen. If it is not specified, it is calculated from the initial text. If the initial text is also not specified, then it is the height of one single space.

Some examples of the label tag:

htmlLabel1.Text = "Some HTML text <label id='lbl1' width='50'>";
htmlLabel1.Text = "Some HTML text <label id='lbl1' value='initial value'>";

Connecting the label in the HTML text with the .NET code

We have thre functions and one event available for connecting the label in the HTML text with the program itself.

  • ChangeLabelText is used for changing the value of the label. It takes two parameters: the label ID and the new label value. If the label text was changed (the label was found), it returns true, else false.
  • GetLabelPos returns the rectangle occupied by the label. It takes two parameters: the label ID and the reference to the Rectangle object. If the label was found and the rectangle set, it returns true, else false. Attention: The rectangle values are in HTMLLabel coordinates, not screen coordinates!
  • RepositionControlOnLabel positions the arbitrary control exactly on the label itself. It takes two parameters: the label ID and the reference to the control. If the label was found, it returns true, else false. Attention: The control that you want to position over the label must be in the same container with the HTMLLabel. You can’t have a TextBox in Panel 1 and an HTMLLabel in Panel 2 and then reposition the TextBox over the HTMLLabel!
  • Recalculated is the event which fires when the text positions on the HTMLLabel is changed so the programmer must rearrange the components.

Here are the signatures:

  • public bool ChangeLabelText(string labelID, string value)
  • public bool GetLabelPos(string labelID, ref Rectangle rect)
  • public void RepositionControlOnLabel(string labelID, Control label)
  • public delegate void RecalculatedEvent(object sender, EventArgs e)


private void myHtmlLabel_Recalculated(object sender, EventArgs e)
  myHtmlLabel.RepositionControlOnLabel("tb", myTextBox);

myHtmlLabel.ChangeLabelText("lbl1", "new value");

Added properties of the HTMLLabel

Compared to the classical Label in .NET CF, HTMLLabel has three more properties:

  • VerticalAlignment controls the vertical alignment of the text inside the HTMLLabel, and can have one of three states: Top, Center, Bottom. The horizontal alignment of the text is controlled by the classical HTML tag <p> and its align property with these possible values: left, right, center.
  • SpaceSize is the space size (in points) between texts. It can have a negative or positive value. When the value is negative, the space size is calculated automatically by dividing the word length by the number of characters. When the value is positive, it means the space size is in points. If the number is zero, then there is no space between words. You will see that even if you set the space size to 0, there is some space between words. This is because the function MeasureString() returns an “incorrect” text size. By “incorrect”, I mean that it returns the size with some space left!
  • ShowBorders is more of a testing property than a property you will use in production. If it is set to true, then the HTMLLabel will draw a rectangle below each text and label, and this rectangle shows the calculated size of the element. As I said, you can use this property to properly set the size of elements.

Tips and tricks

If you want to position a text box inside an HTML text, then you can calculate the exact space needed by using the component size and width!

htmlLabel1.Text = 
  string.Format("Price: <label id='price' width='{0}' height='{1}'>", 
                textBox1.Width, textBox1.Height);

If you want to have enough space for (let us say) 8 numbers, regardless of the font, you can set the initial value of the label. The label size will be set to accommodate this initial value.

htmlLabel1.Text = "Price: <label id='price' value='999999.99'>";

Using the HTMLLabel demo application

The demo application is easy to use, and it will show you different things that the HTMLLabel can do. The main window has three parts:

  1. A selection from where you can choose different test cases.
  2. A textbox with the representation of the Text property (shows raw HTML).
  3. An HTMLLabel with the result.

When you are finished with the pre-prepared test cases, you can directly change the raw HTML in the top textbox and then select the option ‘Show Updated HTML’ from menu (4), which will repaint the HTML. You can also change the settings in the Settings sub form, and the selected settings are instantly applied to the HTMLLabel on the main form.

The code

HTMLLabel has two modules: one is the HTML parser and the other is the HTMLLabel itself.

The HTML parser is quite small and fast. The base was taken from the parser written by Jeff Heaton in his article 'Parsing HTML in Microsoft C#'. I have rewritten his code and profiled it so it is about 70% faster on the mobile device. I have also added support for ‘HTML process instructions’ and ‘HTML comments’.

The basic idea behind HTMLLabel is in splitting the HTML text on the tags and plain text. Text is then split again into words. Each word represents an element, and HTMLLabel calculates the size of each such element and then draws them on the surface.

What can you learn by examining the code?

  • How to write a small and quick text parser.
  • How to use double buffering for faster graphics.
  • How to draw text on a surface with different fonts and colors.
  • How to write a hierarchy of classes instead of one big class with a type field.
  • How to convert a color name and color code to a Color object.
  • How to write custom .NET CF components with custom properties and events.


This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


About the Author

Matjaž Prtenjak
Software Developer (Senior) MERKUR D.D.
Slovenia Slovenia
I am a software developer in one of the largest retailer in our country. My job is (beside else) also in setting some standards in SW development throughout our company.

I have a M.Sc. in computer science and 20 years of experience. I have written 2 books in Slovenian language and both are sold out (the first about C++ language and the second about VBA language)...

You may also be interested in...

Comments and Discussions

Questionlost functionality of TEXT Pin
Member 826622928-Aug-15 0:05
memberMember 826622928-Aug-15 0:05 
Questionlicense Pin
dfigure11-Aug-13 14:42
memberdfigure11-Aug-13 14:42 
AnswerRe: license Pin
Matjaž Prtenjak11-Aug-13 20:18
memberMatjaž Prtenjak11-Aug-13 20:18 
GeneralRe: license Pin
dfigure12-Aug-13 5:38
memberdfigure12-Aug-13 5:38 
GeneralMissingMethodException Pin
wimdevriendt28-Mar-11 8:13
memberwimdevriendt28-Mar-11 8:13 
GeneralRe: MissingMethodException Pin
Matjaž Prtenjak28-Mar-11 9:21
memberMatjaž Prtenjak28-Mar-11 9:21 
Generalref thanks Pin
xmsw6-Dec-09 16:11
memberxmsw6-Dec-09 16:11 
Generalthanks Pin
xmsw3-Dec-09 16:43
memberxmsw3-Dec-09 16:43 
GeneralRe: thanks Pin
Matjaž Prtenjak3-Dec-09 19:52
memberMatjaž Prtenjak3-Dec-09 19:52 
GeneralPretty amazing :) Pin
mysparkle4-Aug-09 8:27
membermysparkle4-Aug-09 8:27 
GeneralRe: Pretty amazing :) Pin
Matjaž Prtenjak4-Aug-09 18:49
memberMatjaž Prtenjak4-Aug-09 18:49 
Generalhello Pin
SeasonLee19-Jul-09 2:42
memberSeasonLee19-Jul-09 2:42 
GeneralRe: hello Pin
Matjaž Prtenjak20-Jul-09 1:13
memberMatjaž Prtenjak20-Jul-09 1:13 
Generalexcellent Pin
connectpalm24-Mar-09 3:15
memberconnectpalm24-Mar-09 3:15 
GeneralRe: excellent Pin
Matjaž Prtenjak24-Mar-09 9:51
memberMatjaž Prtenjak24-Mar-09 9:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170525.1 | Last Updated 3 Mar 2009
Article Copyright 2009 by Matjaž Prtenjak
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid