我正在使用以下代码制作一个高度可调且垂直对齐的文本框。我应该这样做的原因是因为虽然我可以使winform文本框高度可调,但我仍然无法垂直对齐文本框中的文本。所以我决定我必须绘制文本 OnPaint 事件。文本框现在显示正确对齐,但光标仍位于文本框顶部。有没有办法控制这个位置?
public class TextBoxHeightAdjustable : System.Windows.Forms.TextBox
{
public TextBoxHeightAdjustable()
{
this.AutoSize = false;
this.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
}
protected override void OnPaint(PaintEventArgs e)
{
// This never runs no matter what I try!
base.OnPaint(e);
// Create a StringFormat object with the each line of text, and the block
// of text centered on the page.
StringFormat stringFormat = new StringFormat();
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle, stringFormat);
}
}