簡體   English   中英

在 Windows 窗體中更改 ComboBox 邊框顏色

[英]Change ComboBox Border Color in Windows Forms

在我的應用程序中,我添加了組合框,如下圖所示

在此處輸入圖像描述

我已將組合框屬性設置為

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

現在我的問題是如何將邊框樣式設置為組合框,以便它看起來不錯。

我在下面的鏈接中驗證

平面樣式組合框

我的問題與以下鏈接不同。

Windows 窗體應用程序中的通用組合框

如何覆蓋 UserControl 類來繪制自定義邊框?

您可以從ComboBox繼承並覆蓋WndProc並處理WM_PAINT消息並為您的組合框繪制邊框:

在此處輸入圖像描述

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)時需要畫線
  • 要了解有關如何呈現平面組合框的更多信息,您可以查看 .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 Event 中自己繪制邊框:

    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-

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM