如何在WIndows表单应用中应用Border to combobox?

Din*_*lla 9 .net c# combobox winforms

在我的应用程序中,我添加了Combobox,如下图所示

在此输入图像描述

我已将组合框属性设置为

cmbDatefilter.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
Run Code Online (Sandbox Code Playgroud)

而现在我的问题是如何将边框样式设置为组合框以使其看起来不错.

我在下面的链接验证

平面样式组合框

我的问题与以下链接不同.

Windows窗体应用程序中的通用ComboBox

如何覆盖UserControl类来绘制自定义边框?

Rez*_*aei 7

您可以继承ComboBox并覆盖WndProc和处理WM_PAINT消息,并为组合框绘制边框:

在此处输入图片说明 在此处输入图片说明

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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:

  • 在上面的示例中,我使用原色作为边框,您可以添加BorderColor属性或使用其他颜色。
  • 如果您不喜欢下拉按钮的左边框,则可以对该DrawLine方法进行注释。
  • 当控件RightToLeft(0, buttonWidth)到时,您需要画线(Height, buttonWidth)
  • 若要了解有关如何呈现平面组合框的更多信息,可以查看ComboBox.FlatComboAdapter.Net Framework 内部类的源代码。


Equ*_*lsk 4

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

自定义组合框边框示例
左边是正常的,右边是我的例子。