How to prevent TextBox auto scrolls when append text?

后端 未结 2 1476
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 04:58

I have a multi-line TextBox with a vertical scrollbar that logs data from a realtime process. Currently, whenever a new line is added by textBox.AppendText(), the T

2条回答
  •  梦毁少年i
    2021-02-04 05:15

    This seems pretty straight forward but I may be missing something. Use append text to scroll to the position if Autochecked is true and just add the text if you do not wish to scroll.

    Update...I was missing something. You want to set the selection point and then scroll to the caret. See below.

        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
        {
            int caretPos = txtLog.Text.Length;
            txtLog.Text += Environment.NewLine + text;
            txtLog.Select(caretPos, 0);            
            txtLog.ScrollToLine(txtLog.GetLineIndexFromCharacterIndex(caretPos));
        }
    

提交回复
热议问题