我在其中一个申请表中的标签中添加了一个自定义边框,如下所示:
private void ColorMe(PaintEventArgs e)
{
Color myColor = Color.FromArgb(104, 195, 198);
Pen myPen = new Pen(myColor, 1);
e.Graphics.DrawRectangle(myPen,
e.ClipRectangle.Left,
e.ClipRectangle.Top,
e.ClipRectangle.Width - 1,
e.ClipRectangle.Height - 1);
base.OnPaint(e);
}
private void lblDisbs_Paint(object sender, PaintEventArgs e)
{
ColorMe(e);
}
这很好用。 我所要做的就是将 ColorMe(e) 放在每个标签的 Paint 事件中。
但是,我想在整个应用程序的所有表单上使用此方法。 我尝试将我的 ColorMe() 方法放在一个类中以这种方式从多种形式调用它,但它不起作用,说"base 没有 OnPaint 事件"。
我应该如何使此方法在整个应用程序中可用?
创建类LabelWithBorder
从Label
派生它,覆盖OnPaint
方法。
public class LabelWithBorder : Label {
protected override void OnPaint(PaintEventArgs e) {
ColorMe(e);
}
}
将应用中的所有 WinForms 标签替换为标签。
,您可能不应该使用 ClipRectangle
进行绘制,因为它会在控件上生成格式错误的矩形。
如果不使用 Karel Frajtak 的解决方案,它可以尝试创建一个静态类,然后你可以从任何形式调用它:
internal static class LabelBorder {
public static void ColorMe(Rectangle r, PaintEventArgs e) {
r.Inflate(-1, -1);
using (Pen p = new Pen(Color.FromArgb(104, 195, 198), 1))
e.Graphics.DrawRectangle(p, r);
}
}
例:
public Form1() {
InitializeComponent();
label1.Paint += label_Painter;
label2.Paint += label_Painter;
}
void label_Painter(object sender, PaintEventArgs e) {
LabelBorder.ColorMe(((Label)sender).ClientRectangle, e);
}