I’m working on a project updating their WinForms application UI to be more consistent with sizes. TextBox and ComboBox controls have different heights by default, even with the same font. I’ve been able to resize the text boxes by turning off AutoSize, but the text still hugs the top of the control, leaving a gap below.
Is there any way to center the text vertically in the control?
If you’re turning off
AutoSizeon a control, it must be aLabel, sinceTextBoxdoesn’t have anAutoSizeproperty. TheTextAlignproperty of aLabelis of typeContentAligment, so you can set both horizontal and vertical alignment.For various boring reasons,
TextBoxesin Windows are intended to auto-adjust their heights to the font used. To control the height and vertically center the text, you can quickly create a customUserControl, that you can use for replacing all yourTextBoxeswith.On your
UserControl, set theBorderStyletoFixed3Dand theBackColortoSystem.Window. Add aTextBoxand set itsBorderStyletoNone. In the Resize event for the control, add code that makes theTextBoxthe same width as the user control’s client area (accounting for the border pixels) and left-aligns it (i.e.textBox1.Left = 0;) and vertically centers it (e.g.textBox1.Top = (this.Height - textBox1.Height) / 2;).Finally, add to the user control any
TextBox-type properties and events you need (probably just Text andTextChanged, I would guess), and wire them up so that they pass through to theTextBoxinside your control, like this:If you wanted to get super-fancy with this, you could even replace your user control’s
TextAlignproperty with one that is actually of typeContentAlignment(like the Label) and then align the innerTextBoxto match.This same approach works for a
ComboBox, although it will look slightly odd. With theComboBox, you set itsFlatStyleproperty to Flat – otherwise you deal with it the same as aTextBox. It will look odd because the drop-down arrow box won’t be quite at the top and bottom of the panel.