How to prevent TextBox auto scrolls when append text?

后端 未结 2 1475
被撕碎了的回忆
被撕碎了的回忆 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条回答
  • 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));
        }
    
    0 讨论(0)
  • 2021-02-04 05:24

    You have to do it something like this,

    textBox1.AppendText("Your text here");
    // this selects the index zero as the location of your caret
    textBox1.Select(0, 0);
    // Scrolls to the caret :)
    textBox1.ScrollToCaret();
    

    Tested and working on VS2010 c# Winforms, i dont know about WPF but google probably has the answer for you.

    0 讨论(0)
提交回复
热议问题