我有自定义ComboBox
。
我希望在BorderColor
专注时为ComboBox
提供自定义Graphics g = Graphics.FromHwnd(Handle);
Rectangle bounds = new Rectangle(0, 0, Width, Height);
ControlPaint.DrawBorder(g, bounds, BaseConfigurations.StyleColor, ButtonBorderStyle.Solid);
。
为此,我使用以下代码:
MouseHover
问题是,如果我使用ComboBox
事件中的代码
当我在GotFocus
控件上移动鼠标时,我可以看到它有效。
但是,相同的代码在npx webpack
事件中不起作用,我无法弄清楚为什么......感谢任何帮助。
答案 0 :(得分:1)
这是一个继承自ComboBox
的简单类,它公开了两个允许设置Control的Active和Inactive边框的属性。
使用父窗体Paint()
事件完成绘画,仅使选定控件周围的区域无效。
在自定义ComboBox Paint()
事件中订阅了父OnHandleCreated()
事件,以及控件的Enter()
,Leave()
和Move()
事件。
绘制透明边框需要订阅Move()
事件,否则在设计时拖动控件时边框将保留在父客户端区域上。
我还添加了DropDownBackColor()
和DropDownForeColor()
属性,如果自定义ComboBox DrawMode
设置为OwnerDrawVariable
(通常情况下),则会激活这些属性。
这是它的样子:
public class CustomCombo : ComboBox
{
private Color ActionBorderColor = Color.Empty;
public CustomCombo()
{
InitializeComponent();
}
public Color BorderActive { get; set; }
public Color BorderInactive { get; set; }
public Color DropDownBackColor { get; set; }
public Color DropDownForeColor { get; set; }
private void InitializeComponent()
{
this.DrawMode = DrawMode.OwnerDrawVariable;
this.BorderActive = Color.OrangeRed;
this.BorderInactive = Color.Transparent;
this.DropDownBackColor = Color.FromKnownColor(KnownColor.Window);
this.DropDownForeColor = this.ForeColor;
this.HandleCreated += new EventHandler(this.OnControlHandle);
}
protected void OnControlHandle(object sender, EventArgs args)
{
Form parent = this.FindForm();
parent.Paint += new PaintEventHandler(this.ParentPaint);
this.Enter += (s, ev) => { this.InvalidateParent(BorderActive); };
this.Leave += (s, ev) => { this.InvalidateParent(BorderInactive); };
this.Move += (s, ev) => { this.InvalidateParent(Color.Transparent); };
base.OnHandleCreated(e);
}
private void InvalidateParent(Color bordercolor)
{
ActionBorderColor = bordercolor;
Rectangle rect = this.Bounds;
rect.Inflate(2, 2);
this.FindForm().Invalidate(rect);
}
protected void ParentPaint(object sender, PaintEventArgs e)
{
Rectangle rect = this.Bounds;
rect.Inflate(1, 1);
using (Pen pen = new Pen(ActionBorderColor, 1))
e.Graphics.DrawRectangle(pen, rect);
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
using (SolidBrush bkBrush = new SolidBrush(this.DropDownBackColor))
e.Graphics.FillRectangle(bkBrush, e.Bounds);
using (SolidBrush foreBbrush = new SolidBrush(this.DropDownForeColor))
e.Graphics.DrawString(this.Items[e.Index].ToString(),
this.Font, foreBbrush, new PointF(e.Bounds.X, e.Bounds.Y));
e.DrawFocusRectangle();
}
}