如何在WIndows表单应用中应用Border to combobox?
在我的应用程序中,我添加了Combobox,如下图所示
我已将combobox属性设置为
cmbDatefilter.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
现在我的问题是如何将边框样式设置为combobox以使其看起来不错。
我在下面的链接validation
平面样式combobox
我的问题与以下链接不同。
Windows窗体应用程序中的通用ComboBox
如何覆盖UserControl类来绘制自定义边框?
您可以从ComboBox
inheritance并覆盖WndProc
并处理WM_PAINT
消息并为您的combobox绘制边框:
public class FlatCombo:ComboBox { private const int WM_PAINT = 0xF; private int buttonWidth= SystemInformation.HorizontalScrollBarArrowWidth; protected override void WndProc(ref Message m) { base.WndProc(ref m); if (m.Msg == WM_PAINT) { using (var g = Graphics.FromHwnd(Handle)) { using (var p = new Pen(this.ForeColor)) { g.DrawRectangle(p, 0, 0, Width - 1, Height - 1); g.DrawLine(p, Width - buttonWidth, 0, Width - buttonWidth, Height); } } } } }
注意:
- 在上面的示例中,我使用前面颜色作为边框,您可以添加
BorderColor
属性或使用其他颜色。 - 如果您不喜欢下拉按钮的左边框,则可以注释
DrawLine
方法。 - 当控件是
RightToLeft
时,你需要绘制线条(0, buttonWidth)
到(Height, buttonWidth)
- 要了解有关如何渲染平面combobox的更多信息,您可以查看.Net Framework的内部
ComboBox.FlatComboAdapter
类的源代码。
CodingGorilla有正确的答案,从ComboBox派生出你自己的控件然后自己画边框。
这是一个绘制1像素宽的深灰色边框的工作示例:
class ColoredCombo : ComboBox { protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); using (var brush = new SolidBrush(BackColor)) { e.Graphics.FillRectangle(brush, ClientRectangle); e.Graphics.DrawRectangle(Pens.DarkGray, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1); } } }
正常在左边,我的例子在右边。
另一种选择是在Parent控件的Paint事件中自己绘制边框:
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint Panel1.CreateGraphics.DrawRectangle(Pens.Black, ComboBox1.Left - 1, ComboBox1.Top - 1, ComboBox1.Width + 1, ComboBox1.Height + 1) End Sub
-OO-