111,093
社区成员




public class FuckBox : Control
{
private FuckArg[] _Items = new FuckArg[0];
public FuckArg[] Items {
get { return _Items; }
set {
if (value == _Items || value == null) return;
_Items = value;
this.Invalidate();
this.Height = 0;//会触发SetBoundsCore
}
}
private Size _ColorBoxSize = new Size(20, 15);
public Size ColorBoxSize {
get { return _ColorBoxSize; }
set {
if (value == _ColorBoxSize) return;
_ColorBoxSize = value;
this.Invalidate();
}
}
private int _Value;
public int Value {
get { return _Value; }
set {
if (value == _Value || value < 0 || value > this.Items.Length) return;
_Value = value;
this.Invalidate();
}
}
public FuckBox() {
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
}
protected override void OnPaint(PaintEventArgs e) {
Graphics g = e.Graphics;
for (int i = 0; i < this.Items.Length; i++) {
using (SolidBrush sb = new SolidBrush(this.Items[i].Color)) {
int h = this.Height - i * (this._ColorBoxSize.Height + 1) - this._ColorBoxSize.Height - 1;
if (i < this.Value)//只绘制 小于 value 的框
g.FillRectangle(sb, 1, h, this._ColorBoxSize.Width, this._ColorBoxSize.Height);
g.DrawRectangle(Pens.Black, 1, h, this._ColorBoxSize.Width - 1, this._ColorBoxSize.Height - 1);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Far; //水平方向靠右对齐
sf.LineAlignment = StringAlignment.Center; //锤子方向 中间对齐
//绘制文字
g.DrawString(
this.Items[i].Text,
this.Font,
Brushes.Black,
new Rectangle(this.ColorBoxSize.Width + 2, h, this.ColorBoxSize.Width, this.ColorBoxSize.Height),
sf);
}
}
base.OnPaint(e);
}
protected override void OnMouseDown(MouseEventArgs e) {
this.Focus();
base.OnMouseDown(e);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
switch (keyData) {//处理方向键
case Keys.Up: this.Value++; return true;
case Keys.Down: this.Value--; return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
//自动设置大小
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
width = this._ColorBoxSize.Width + 20;
height = (this.ColorBoxSize.Height + 1) * this.Items.Length + 1;
if (height < 5) height = 6;
base.SetBoundsCore(x, y, width, height, specified);
}
}
public class FuckArg//保存信息的类
{
private Color _Color = Color.Gray;
[Description("选中时候的颜色")]
public Color Color {
get { return _Color; }
set { _Color = value; }
}
private string _Text = "0";
[Description("绘制的文本")]
public string Text {
get { return _Text; }
set { _Text = value; }
}
public override string ToString() {//方便好看
return this._Text + "|" + this._Color;
}
}
控件 三个属性
Items 需要绘制的方块和文本 全部在这里 [选中时候的颜色,文本] 没选中的默认透明
ColorBoxSize 绘制时候 颜色框的大小
Value 默认选择的位置 如图中的是6 就是从下往上 选择6个