Question

I have created a button using the code below. Adding the start.Text="Start"; statement does nothing. How do I add a label to my button?

public MainForm()
{
    InitializeComponent();

    myButtonObject start = new myButtonObject();
    EventHandler myHandler = new EventHandler(start_Click);
    start.Click += myHandler;
    start.Location = new System.Drawing.Point(200, 500);
    start.Size = new System.Drawing.Size(101, 101);
    start.Text="Start";
    //  start.TextAlign = new System.Drawing.ContentAlignment.MiddleCenter;
    this.Controls.Add(start);
}

public class myButtonObject : UserControl
{
    // Draw the new button. 
    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics graphics = e.Graphics;
        Pen myPen = new Pen(Color.Black);
        // Draw the button in the form of a circle
        graphics.FillEllipse(Brushes.Goldenrod, 0, 0, 100, 100);        
        graphics.DrawEllipse(myPen, 0, 0, 100, 100);        
        myPen.Dispose();
    }
}
Was it helpful?

Solution 2

You should draw the button's text yourself in the OnPaint method:

TextRenderer.DrawText(graphics, Text, Font, new Point(5, 5), SystemColors.ControlText);

Where new Point(5, 5) - is a top left position of the text.

OTHER TIPS

You have implemented your own button as a user control. Since you are implementing OnPaint to provide your own draw functionality, you need to implement all the functionality like drawing the text too.

If you want to go down this route then you also need to add the logic to draw the text on the control in your OnPaint method. This can be done using the graphics.DrawString method.

See http://msdn.microsoft.com/en-us/library/system.drawing.graphics.drawstring.aspx

You also need to call graphics.dispose.

If you aren't familiar with this, then it might be simpler to use a UserControl and add a label to it, or something similar, and then to draw your circle shape on the top of that.

You paint the button ok but you don't draw the text.

A usercontrol doesn't do this by itself.

Just add something like this to the paint commands:

graphics.DrawString(Text, yourfont, yourBrush, x, y);   

you must and may have to decide freely on x, y font and brush.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top