调整大小后显示所有 TextBox 文本






4.91/5 (19投票s)
如果 TextBox 足够宽以显示所有文本,此方法可确保在调整大小后文本可见。
引言
如果 TextBox 太窄而无法显示所有文本,则在启动时会显示文本的末尾。
如果您将其调整为可以显示整个字符串的宽度,则 TextBox 不会重新定位文本以显示所有文本。
此代码将重置文本位置以显示所有文本,同时保留任何文本选择和光标位置。
背景
.NET TextBox 控件只是旧 Win32 编辑框控件的包装器。 这限制了它的功能,并使其难以自定义。 即使是像 调整 TextBox 的高度 这样简单的任务,也需要您使用复杂的解决方法来完成。
当您调整 TextBox 大小时,其中一些文本位于控件的左边缘之外,它永远不会重新定位文本以显示控件可以处理的最大数量。 为了克服此限制,我们需要修改 TextBox 文本选择。
使用代码
要重置 TextBox 中的可见文本,我们需要将光标(游标)位置更改为字符串的开头,然后再更改回结尾。 但是,这样做会丢失用户在调整大小之前可能进行的任何选择。 此例程将确定控件中选择的内容,重置光标位置,然后恢复用户的选择。
Visual Basic
Private Sub SetAllTextVisible(ByRef tbTextBox As TextBox)
Dim iSelectStart As Integer
Dim iSelectLength As Integer
' Get the current selection so we can re-select it.
iSelectStart = tbTextBox.SelectionStart
iSelectLength = tbTextBox.SelectionLength
' De-select everything and set the cursor to
' the start of the line
tbTextBox.Select(0, 0)
tbTextBox.SelectionStart = 0
' Restore the user's original selection
tbTextBox.Select(iSelectStart, iSelectLength)
End Sub
C#
public void SetAllTextVisible(TextBox tbTextBox)
{
int startselect;
int selectlength;
// Get the current selection so we can re-select it
startselect = tbTextBox.SelectionStart;
selectlength = tbTextBox.SelectionLength;
// De-select everything and set the cursor to the
// start of the line.
tbTextBox.Select(0, 0);
tbTextBox.SelectionStart = 0;
// Restore the user's original selection
tbTextBox.Select(startselect, selectlength);
}
用户控件
或者,您可以创建一个新的 UserControl 类,并将类声明中的继承更改为从 UserControl 到 TextBox。 覆盖 OnSizeChanged 事件以调用 SetAllTextVisible 例程。
重要提示:如果您将类的继承从 UserControl 更改为 TextBox,则需要打开 UserControll.Designer 代码并删除 Autoscale 属性。
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
//Comment the line below when changing inheritence from UserControl
//to Textbox.
//this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
}
public partial class ShowAllTextBox : TextBox
{
public ShowAllTextBox()
{
InitializeComponent();
}
protected override void OnSizeChanged(EventArgs e)
{
SetAllTextVisible();
base.OnSizeChanged(e);
}
public void SetAllTextVisible()
{
int startselect;
int selectlength;
// Get the current selection so we can re-select it
startselect = this.SelectionStart;
selectlength = this.SelectionLength;
// De-select everything and set the cursor to the
// start of the line.
this.Select(0, 0);
this.SelectionStart = 0;
// Restore the user's original selection
this.Select(startselect, selectlength);
}
}
尽情享用!