我有一个带有垂直滚动条的多行TextBox,它可以记录实时进程中的数据.目前,无论何时添加新行textBox.AppendText(),TextBox都会滚动到底部,以便您可以看到最后一个条目,这很棒.但是我有一个复选框来决定何时允许TextBox自动滚动.反正有没有这样做?
注意:
textBox.Text += text,但TextBox始终滚动到顶部.如果我们有一个解决方案,那么还有一个问题是当TextBox附加文本时,当用户使用滚动条查看TextBox中的其他位置时,如何防止TextBox自动滚动?
private void OnTextLog(string text)
{
    if (chkAutoScroll.Checked)
    {
        // This always auto scrolls to the bottom.
        txtLog.AppendText(Environment.NewLine);
        txtLog.AppendText(text);
        // This always auto scrolls to the top.
        //txtLog.Text += Environment.NewLine + text;
    }
    else
    {
        // I want to append the text without scrolls right here.
    }
}
Run Code Online (Sandbox Code Playgroud)
更新1:正如saggio建议的那样,我也认为这个问题的解决方案是确定当前文本中第一个字符在TextBox中显示的位置,然后再附加文本并在之后恢复它.但是怎么做呢?我试着像这样记录当前的光标位置,但它没有帮助:
int selpoint = txtLog.SelectionStart;
txtLog.AppendText(Environment.NewLine);
txtLog.AppendText(text);
txtLog.SelectionStart = selpoint;
Run Code Online (Sandbox Code Playgroud)
更新2 (问题已解决):我找到了一个可以在Stack Overflow上解决我的问题的解决方案.我已经优化了他们的代码以适应我的问题,如下所示:
// Constants for …Run Code Online (Sandbox Code Playgroud)