views:

67

answers:

2

Can I change the appearance of a Winforms ComboBox so that a Combobox with DropDownStyle = DropDownList looks more like one that is DropDownStyle = DropDown. The functional difference between them is that the former doesn't allow for user entered values, the problem is that it's default color scheme looks grayed out and doesn't match with textboxes on the same dialog.

A: 

You could try to change the FlatStyle property and see if you get something more to your liking. If you really want it to look like it does with DropDownStyle set to DropDown, you could set the DropDownStyle to DropDown and eat the KeyPress event:

private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = true;
}

Still, I would probably not do this as the appearance of the ComboBox is a visual cue to the user indicating whether they should be able to type in the text area or not.

adrift
At least in win7 that only changes the border. The interior of the control remains a gray gradient similar to the form background. IIRC in XP the difference between the two drop styles was much less dramatic.
Dan Neely
+2  A: 

you can get DropDown appearance from DropDownList style by changing DrawMode property to DrawMode.OwnerDrawFixed and handling item painting by yourself (thankfully, that's easy). Sample class, implementing this idea:

public class ComboBoxEx : ComboBox
{
    public ComboBoxEx()
    {
        base.DropDownStyle = ComboBoxStyle.DropDownList;
        base.DrawMode = DrawMode.OwnerDrawFixed;
    }

    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        e.DrawBackground();
        if(e.State == DrawItemState.Focus)
            e.DrawFocusRectangle();
        var index = e.Index;
        if(index < 0 || index >= Items.Count) return;
        var item = Items[index];
        string text = (item == null)?"(null)":item.ToString();
        using(var brush = new SolidBrush(e.ForeColor))
        {
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            e.Graphics.DrawString(text, e.Font, brush, e.Bounds);
        }
    }
}
max
Interesting. Is that something you wrote from scratch or pulled from the framework using reflection?
Dan Neely
It's written from scratch. In fact, this behavior is not really expected. Some time ago I needed to implement a combo box with customized item painting and noticed that changing `DrawMode` property also affects control style, forcing it to `DropDown`.
max
+1, @max: very nice!
adrift