我有一个小应用程序,其中包含一个按钮和一个标签。该按钮具有自定义的OnPaint方法,使其看起来独特。但是,标签目前没有。然而,标签似乎出现在按钮内部,原因不明。看看这个:
为了澄清问题,我已禁用了渲染填充矩形,因为它大多数情况下覆盖了问题。这是我的按钮的OnPaint代码:
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
g.SmoothingMode = SmoothingMode.HighQuality;
Pen p = new Pen (Color.Black, 2);
Rectangle fillRect = new Rectangle (e.ClipRectangle.X, e.ClipRectangle.Y, e.ClipRectangle.Width - 2, e.ClipRectangle.Height - 2);
Brush b;
if (MouseHovering)
{
b = new SolidBrush (Color.DarkSlateGray);
}
else
{
b = new SolidBrush (Color.Gray);
}
//g.FillRectangle (b, fillRect);
g.DrawRectangle (p, e.ClipRectangle);
//g.DrawString (Text, new Font ("Arial", 8), new SolidBrush (Color.Black), new Point (4, 4));
}
以下是在主表单类中创建标签和按钮的代码:
label = new Label ();
label.Text = "Hello World";
label.Top = 15;
label.Left = 180;
label.AutoSize = true;
Controls.Add (label);
CButton b = new CButton ();
b.Text = "Click me for a new sentence";
b.AutoSize = true;
b.Top = 10; b.Left = 10;
Controls.Add (b);
上述代码在构造函数中调用。然后当按钮被按下时,标签文本将被设置为以下内容:
label.Text = Specifier + " " + Verb + " a " + CommonNoun;
那么这里发生了什么?该怎么解决?如果您需要其他代码来理解问题,请不要犹豫,随时联系我们。
g.Clear(BackColor)
。同时不要使用剪切矩形,只需使用Rectangle(0, 0, this.Width, this.Height);
,确保在结束时处理好你的GDI对象(b.Dispose()
,p.Dispose()
)。 - Ron Beyer