更新时间:2023-12-04 13:27:46
您可以使用:
使用这种形式的选择,当控件不包含任何文本时(即当文本为空字符串时),您将不会有例外.
此外,您避免使用 Lines 属性:此值未缓存,因此每次使用时都需要对其进行评估,每次解析 TextBoxBase 控件的全部内容.
Using this form of selection, you won't have exceptions when the Control doesn't contain any text (i.e., when the text is an empty string).
Also, you avoid to use the Lines property: this value is not cached, so it needs to be evaluated each time you use it, parsing - each time - the whole content of a TextBoxBase control.
Private Sub TextBoxLog_TextChanged(sender As Object, e As EventArgs) Handles TextBoxLog.TextChanged
Dim tBox = DirectCast(sender, TextBoxBase)
Dim lastLine As Integer = tBox.GetLineFromCharIndex(tBox.TextLength)
Dim lineFirstIndex As Integer = tBox.GetFirstCharIndexFromLine(lastLine)
tBox.Select(lineFirstIndex, tBox.TextLength - lineFirstIndex)
End Sub
► 由于您使用 Button 向 TextBox 控件添加文本,我建议设置 TextBox/RichTextBox HideSelection 属性设置为 False
,否则您可能实际上看不到所选文本.如果您不喜欢将 HideSelection
设置为 False,那么您需要在 Button.Click 处理程序中调用 [TextBox].Focus()
以查看文本突出显示.
► Since you're adding text to the TextBox control using a Button, I suggest to set the TextBox/RichTextBox HideSelection property to False
, otherwise you may not actually see the selected text. If you don't like to have HideSelection
set to False, then you need to call [TextBox].Focus()
, in the Button.Click handler, to see the text highlighted.
在这里,我将 sender
转换为 TextBoxBase (Dim tBox = DirectCast(sender, TextBoxBase)
),因此您可以将此方法应用于任何其他 TextBox 或 RichTextBox,而无需更改控件的名称.
Here, I'm casting sender
to TextBoxBase (Dim tBox = DirectCast(sender, TextBoxBase)
), so you can adapt this method to any other TextBox or RichTextBox without changing the name of the Control.
sender
参数表示引发事件的控件.sender
argument represents the Control that raised the event.