This can be achieved by adding an event handler to the label's paint event
Add the following code to the InitializeComponent() method
this.label1.Paint += new System.Windows.Forms.PaintEventHandler(this.label1 _Paint);
And write code similar to the following in the paint event handler method. You can change the brush and pen and other parameters as per requirement.
The label size should be large enough to accomodate the entire text.
private void label1_Paint(object sender, PaintEventArgs e)
{
//calculate bounds for rectangle
int rectx = 5; //margin from top and bottom of label border
int recty = 5; //margin from left and right sides of label border
int rectWidth = label1.Width - 10;
int rectHeight = label1.Height - 10;
Graphics gr = e.Graphics;
//specify color and width of line to draw rectangle
System.Drawing.Pen pen = new Pen(System.Drawing.Color.BlueViolet, 1.1F);
//this call draws the rectangle with specified color and line width
gr.DrawRectangle(pen, rectx, recty, rectWidth, rectHeight);
//calculate center position for string
String s = "Label \nText";
Font f = new Font("Courier New", 12F); //font name and size
//get the size of string (width and height) in pixels, pass string and its font as parameters
SizeF stringSize = gr.MeasureString(s,f);
//now calculte the starting point (x,y) for the string
//the formula is margin + (rectangle width - string width) / 2
float strX = rectx + (rectWidth - stringSize.Width) / 2;
float strY = recty + (rectHeight - stringSize.Height) / 2;
//choose a brush to draw the string
System.Drawing.Brush br = new SolidBrush(System.Drawing.Color.Chocolate);
//this call draws the string at the specified position with the chosen brush
gr.DrawString(s, f, br, strX, strY);
}
Hope this helps.
--
Sameeksha,
MCP (.NET)
"Stuart Norris" wrote:
Dear Readers,
I am attempting to draw box around some text using unicode on
multiline label. The label is forty characters wide and 12 lines deep.
I have been trying to draw a box around text (centered in the label)
on this label.
My font on this label is Courier new - hence fixed width character
cells.
I have tried using the Box Drawing unicode in with the Courier new
font, \u250c, \u2500, \u2510 etc.
this.Label.Text="\u250f\u2501\u2513\r\n\u2503 \u2503";
However there is a gap between the characters?
-----------
| Label |
-----------
Is there a way to draw a proper box around text on a label with
Courier new font using unicode?
Alternatively is it possible to draw the text labels yourself like
ownerdrawn menu buttons?
Where I calculate the width and height of the label and my text size
in the required font and then
draw a rectangle around my text in the centre of the label? Any
examples?
Any suggestion most welecome.
Stuie