当DrawMode不正常时,我的ComboBox看起来很糟糕

alc*_*vil 6 c# combobox winforms drop-down-menu

当ComboBox的DropDownStyle是DropDownList并且DrawMode是Normal时 - 它看起来不错,但是当我将DrawMode更改为OwnerDrawFixed时 - 它看起来非常糟糕(类似于带有箭头的TextBox下拉).当DrawMode不正常时,有什么解决方案可以让它看起来很好吗?

看起来像那样: 看起来像那样

我希望它看起来像那样: 我希望它看起来像那样

alc*_*vil 2

我在这里找到了VB中的解决方案:how-to-make-a-custom-combobox-ownerdrawfixed-looks-3d-like-the-standard-combobo 添加了一些用于绘制文本和箭头的代码。有用 :)

class MyComboBox: ComboBox
{
    public MyComboBox()
    {
        this.SetStyle(ControlStyles.Opaque | ControlStyles.UserPaint, true);
        Items.Add("lol");
        Items.Add("lol2");  
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (DroppedDown)
            ButtonRenderer.DrawButton(CreateGraphics(), new System.Drawing.Rectangle(ClientRectangle.X - 1, ClientRectangle.Y - 1, ClientRectangle.Width + 2, ClientRectangle.Height + 2), PushButtonState.Pressed);
        else
            ButtonRenderer.DrawButton(CreateGraphics(), new System.Drawing.Rectangle(ClientRectangle.X - 1, ClientRectangle.Y - 1, ClientRectangle.Width + 2, ClientRectangle.Height + 2), PushButtonState.Normal);
        if (SelectedIndex != -1)
        {
            Font font;
            if (SelectedItem.ToString().Equals("lol"))
                font = new Font(this.Font, FontStyle.Bold);
            else
                font = new Font(this.Font, FontStyle.Regular);
            e.Graphics.DrawString(Text, font, new SolidBrush(Color.Black), 3, 3);
        }
        if (DroppedDown)
            this.CreateGraphics().DrawImageUnscaled(new Bitmap("c:\\ArrowBlue.png"), ClientRectangle.Width - 13, ClientRectangle.Height - 12);
        else
            this.CreateGraphics().DrawImageUnscaled(new Bitmap("c:\\ArrowGray.png"), ClientRectangle.Width - 13, ClientRectangle.Height - 12);
        base.OnPaint(e);
    }
Run Code Online (Sandbox Code Playgroud)

我不知道如何消除鼠标进入和离开组合框时的闪烁。当启用 DoubleBuffering 时,ComboBox 为黑色。但对我来说效果很好。

  • 频繁调用“CreateGraphics”会泄漏 GDI 资源。您应该使用包装在“using()”块中的单个“Graphics”对象,以确保调用其“Dispose”方法。 (2认同)