Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - Change ComboBox Border Color in Windows Forms

In My Application i have added Combobox as shown in below picture

enter image description here

i have set the combobox property as

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

And now my question is how to set border style to combobox so that it will look nice.

I verified in below link

Flat style Combo box

My question is different from below link's.

Generic ComboBox in Windows Forms Application

How to override UserControl class to draw a custom border?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can inherit from ComboBox and override WndProc and handle WM_PAINT message and draw border for your combo box:

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);
                }
            }
        }
    }
}

Note:

  • In the above example I used fore color for border, you can add a BorderColor property or use another color.
  • If you don't like the left border of dropdown button, you can comment that DrawLine method.
  • You need to draw line when the control is RightToLeft from (0, buttonWidth) to (Height, buttonWidth)
  • To learn more about how to render a flat combo box, you can take a look at source code of internal ComboBox.FlatComboAdapter class of .Net Framework.

Flat ComboBox

You may also like Flat ComboBox:

enter image description here enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...