CSharp .Net Tutorial: Draw Strings on a From

James Cloud
In Visual Basic 6 and other less powerful languages the programmer could easily print or draw text on the screen using the Print command, supplying the desired string as a parameter.However these print function lack many features such as brush customization. Drawing string is a bit more complicated using the Visual CSharp .Net Framework programming language, but with a little complication comes a lot more control and power.

Simply follow this tutorial if you want to learn how to draw or print text string anywhere on your form.

Drawing String on a Form

The first step to successfully drawing text or strings on your form is to create an easily reusable and accessible void called DrawString. Create this void using the code found below.

public void DrawString(Form Frm, String Str, int Size, Color Clr, float X, float Y)
{
//Setup Graphics, Brushes, Fonts, and Formatting
System.Drawing.Graphics myGraphics = Frm.CreateGraphics();
System.Drawing.Font myFont = new Font("Arial", Size);
System.Drawing.SolidBrush myBrush = new SolidBrush(Clr);
System.Drawing.StringFormat myFormat = new StringFormat();

//Draw the Actual String
myGraphics.DrawString(Str, myFont, myBrush, X, Y, myFormat);

//Dispose of Left Overs
myFont.Dispose();
myBrush.Dispose();
myGraphics.Dispose();
}

Now, in your form's Paint event simply call your newly created DrawString void while supplying your desired parameters, like so:

private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawString(this, "My String", 8, Color.Black, 0, 0);
}

This will draw the string "My String" at the coordinates, left 0, right 0 using the size 8 and the color black. Of course you can replace these parameter with your desired string, size, color, and coordinates.

Conclusion

This is a simple and bare bones way of drawing text strings on your form. However with some tweaking to the DrawString void you can add extra and more advanced functionality, such as font type, brush style, bold, underline, strikeout, and more, to your the DrawString function.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.