Contents
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:
- 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.
- It can replace a lot of different Label objects and combine them together.
- It can (as a matter of fact, it does) speed up the
InitializeComponent()
function. That is quite important in mobile development!
- It has a
Click
event (missing in the Label
class in .NET CF).
- 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!
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.
Using the code is easy:
- Download the source code and add the files HTMLParser.cs and HTMLLabel.cs into your mobile project.
- Compile the code so Visual Studio can create the
HTMLLabel
object on the tool bar.
- Place the
HTMLLabel
object from the tool bar on a form.
- Change its
Text
property to some HTML text and you are done.
<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 (www.w3schools.com), or a hexadecimal representation of a color in the form of #RRGGBB.
<pre>
means non-breaking text.
<br>
means text break.
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>"
In drawing HTML text on the screen, there are three essential steps:
- parsing the HTML text
- calculating text positioning based on font and alignment
- 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:
htmlLabel1.Text = "Desc: <label id='desc' width='100'>"
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'>";
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)
Examples:
private void myHtmlLabel_Recalculated(object sender, EventArgs e)
{
myHtmlLabel.RepositionControlOnLabel("tb", myTextBox);
}
myHtmlLabel.ChangeLabelText("lbl1", "new value");
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.
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'>";
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:
- A selection from where you can choose different test cases.
- A textbox with the representation of the
Text
property (shows raw HTML).
- 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.
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.
- 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.