Skip to main content
 首页 » 编程设计

c#之如何将标签/文本添加到手动创建的按钮

2024年02月13日14傻小

我使用下面的代码创建了一个按钮。添加 start.Text="Start"; 语句没有任何作用。如何为我的按钮添加标签?

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(); 
    } 
} 

请您参考如下方法:

您已经将自己的按钮实现为用户控件。由于您要实现 OnPaint 以提供自己的绘图功能,因此您还需要实现所有功能,例如绘制文本。

如果你想沿着这条路走下去,那么你还需要添加逻辑来在你的 OnPaint 方法中的控件上绘制文本。这可以使用 graphics.DrawString 方法来完成。

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

您还需要调用 graphics.dispose。

如果您对此不熟悉,那么使用 UserControl 并向其添加标签或类似内容,然后在其顶部绘制圆形可能会更简单。