我遇到了同样的问题并构建了一些可以正常工作的东西:
public class TextBox : System.Windows.Forms.TextBox
{
public TextBox()
{
BorderStyle = BorderStyle.None;
Text = "__________"; //Sometime this doesn't work while creating the control in design mode ; don't know why
}
//protected override void OnFontChanged(EventArgs e)
//{
// base.OnFontChanged(e);
// RefreshHeight();
//}
bool loaded = false;
protected override void OnCreateControl()
{
if(!loaded)
RefreshHeight();
base.OnCreateControl();
}
private void RefreshHeight()
{
loaded = true;
Multiline = true;
Size s = TextRenderer.MeasureText(Text, Font, Size.Empty, TextFormatFlags.TextBoxControl);
MinimumSize = new Size(0, s.Height + 1);
Multiline = false;
}
}
我曾经bool loaded = false
避免应用程序因为OnCreateControl
. TextBox控件没有OnLoad
事件(我愿意接受另一种方法)。
OnFontChanged
如果您的应用在运行时更改字体大小,则可以取消注释
MinimumSize = new Size(0, s.Height + 1);
我加了 1以避免任何错误MeasureText