You can derive from NumericUpDown
, add a BorderColor
property, override OnPaint
and draw border based on the border color.
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
public class MyNumericUpDown : NumericUpDown
{
private Color borderColor = Color.Blue;
[DefaultValue(typeof(Color), "0,0,255")]
public Color BorderColor
{
get { return borderColor; }
set
{
if (borderColor != value)
{
borderColor = value;
Invalidate();
}
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (BorderStyle != BorderStyle.None)
{
using (var pen = new Pen(BorderColor, 1))
e.Graphics.DrawRectangle(pen,
ClientRectangle.Left, ClientRectangle.Top,
ClientRectangle.Width - 1, ClientRectangle.Height - 1);
}
}
}
Note: Just as a side note, this control raises paint event and if for any reason someone wants to achieve the same behavior without inheritance they can handle the Paint event and draw the border; however as a general solution and a reusable one, a derived control makes more sense.
private void numericUpDown_Paint(object sender, PaintEventArgs e)
{
var c = (NumericUpDown)sender;
ControlPaint.DrawBorder(e.Graphics, c.ClientRectangle,
Color.Red, ButtonBorderStyle.Solid);
var r = new Rectangle(1, 1, c.Width - 2, c.Height - 2);
e.Graphics.SetClip(r);
}
FlatNumericUpDown
I've created a FlatNumericUpDown which supports BorderColor
and ButtonHighlightColor
. You can download or clone it:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…