A .NET Framework Text and Font Primer
- Basic Text Display
- Windows Fonts
- Font Class
- Displaying Text
- Other Format Settings
Almost any application you write has to display text in some form or another. The .NET Framework provides the developer with a full set of tools for displaying text onscreen and also sending it to the printer. This article takes a look at these tools and how to use them. It also gives a greater understanding of how Windows fonts work.
Basic Text Display
Let’s start with a simple text display task: writing some text to the screen in a specific font and at a specific location. There are three steps:
- Create a Font object representing the font to use.
- Create a Brush object to draw the text.
- Call the Graphics object’s DrawString() method, passing as arguments the Font and Brush objects, the message, and the desired display coordinates.
The following code goes in the form’s Paint() event procedure:
private void Form1_Paint(object sender, PaintEventArgs e) { Font f = new Font("Arial", 32); SolidBrush br = (SolidBrush)Brushes.Black; Graphics g = e.Graphics; string msg = "Text in .NET!"; g.DrawString(msg, f, br, 25, 25); }
The output is shown in Figure 1.
Figure 1 Basic text display in .NET is quite simple.
Pretty simple, no? But there’s a lot more to .NET’s text capabilities. First, you need to learn a little about fonts.