ComboBox Text Align Vertically Center

后端 未结 2 1154
旧时难觅i
旧时难觅i 2021-01-21 08:05

I created the custom combobox on .net framework 1.1, i can custom draw dropdown items, but i can\'t set or draw the combobox text on Middle Left , combobox text always render t

2条回答
  •  暖寄归人
    2021-01-21 08:32

    ok, below code doesn't answer the actual question about the Text portion; Hans got it right, as usual.

    I keep the answer because I think it does a few things better than OP code..

        if (!DesignMode)
        {
            if (e.Index > -1)
            {
               using (StringFormat fmt = new StringFormat() 
                 { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center })
               {
    
                if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                {
                    e.Graphics.FillRectangle(SystemBrushes.MenuHighlight, e.Bounds);
                    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), 
                                            e.Font,SystemBrushes.HighlightText, e.Bounds, fmt);
                }
                else
                {
                    e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
                    e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), 
                                            e.Font, SystemBrushes.MenuText,e.Bounds, fmt);
                }
             }
          }
        }
    

    Instead of calculating a centered position I use the DrawString overload that takes a target rectangle and add a StringFormat to center in both directions. StringFormat was available since .Net 1.1 and indeed is IDisposable, so we should dipose of each we create, best in a using clause..

    Note that for drawing controls the use of TextRenderer is encouraged but only came with .Net 2.0.

    Also note that I substituted the Brushes for SystemBrushes..

    Also: My ComboBox doesn't place the text in its Text portion top-left but middle-left. Maybe the old .Net1.1 control is the culprit?

提交回复
热议问题