c# - 在 Windows 窗体中更改 ComboBox 边框颜色

标签 c# .net winforms combobox

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

enter image description here

我已将组合框属性设置为

cmbDatefilter.FlatStyle = System.Windows.Forms.FlatStyle.Flat;

现在我的问题是如何为组合框设置边框样式,以便它看起来不错。

我在下面的链接中验证了

Flat style Combo box

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

Generic ComboBox in Windows Forms Application

How to override UserControl class to draw a custom border?

最佳答案

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

enter image description here

using System;
using System.Drawing;
using System.Windows.Forms;

public class FlatCombo : ComboBox
{
    private const int WM_PAINT = 0xF;
    private int buttonWidth = SystemInformation.HorizontalScrollBarArrowWidth;
    Color borderColor = Color.Blue;
    public Color BorderColor
    {
        get { return borderColor; }
        set { borderColor = value; Invalidate(); }
    }
    protected override void WndProc(ref Message m)
    {
        base.WndProc(ref m);
        if (m.Msg == WM_PAINT && DropDownStyle != ComboBoxStyle.Simple)
        {
            using (var g = Graphics.FromHwnd(Handle))
            {
                using (var p = new Pen(BorderColor))
                {
                    g.DrawRectangle(p, 0, 0, Width - 1, Height - 1);

                    var d = FlatStyle == FlatStyle.Popup ? 1 : 0;
                    g.DrawLine(p, Width - buttonWidth - d,
                        0, Width - buttonWidth - d, Height);
                }
            }
        }
    }
}

注意:

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

平面组合框

您可能还喜欢Flat ComboBox :

enter image description here enter image description here

关于c# - 在 Windows 窗体中更改 ComboBox 边框颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34877280/

相关文章:

c# - NotifyIcon 的问题不会在 Winforms 应用程序上消失

c# - 如何将 Metro App 部署到桌面?

c# - 如何在 Visual C# .NET Web 元素中添加对所有 Web 窗体的 CSS 样式表引用

c# - 如何强制 Regex.Replace 匹配 '/s'(将字符串视为单行)正则表达式修饰符

c++ - Visual Studio 2017 - 找不到 Visual C++ Windows 窗体

c# - 简单绑定(bind) .NET 数据绑定(bind)不起作用

c# - 认证中的一些误区

c# - WPF 列表框选择已更改

c# - 如何从.Net代码获取IP地址

C# Telnet 库