代码之家  ›  专栏  ›  技术社区  ›  GWLlosa

如何自动滚动到多行文本框的底部?

  •  249
  • GWLlosa  · 技术社区  · 17 年前

    我有一个.Multiline属性设置为true的文本框。每隔一段时间,我会给它添加新的文本行。我想文本框自动滚动到最底部的条目(最新的),每当一个新行被添加。我如何做到这一点?

    11 回复  |  直到 17 年前
        1
  •  465
  •   Community Mohan Dere    9 年前

    每隔一段时间,我会给它添加新的文本行。我想文本框自动滚动到最底部的条目(最新的),每当一个新行被添加。

    如果你使用 TextBox.AppendText(string text) ,它将自动滚动到新添加文本的末尾。如果您在循环中调用它,它可以避免闪烁的滚动条。

    .Text 所有物尽管这可能取决于你打电话的频率;我用一个紧密的循环进行测试。


    如果在显示文本框之前调用它,或者如果文本框不可见(例如在TabPanel的不同选项卡中),则不会滚动。看见 TextBox.AppendText() not autoscrolling . 这可能很重要,也可能不重要,这取决于用户看不到文本框时是否需要自动滚动。

    似乎其他答案中的替代方法在这种情况下也不起作用。一种方法是在屏幕上执行额外的滚动 VisibleChanged 活动:

    textBox.VisibleChanged += (sender, e) =>
    {
        if (textBox.Visible)
        {
            textBox.SelectionStart = textBox.TextLength;
            textBox.ScrollToCaret();
        }
    };
    

    内部,, AppendText 是这样做的:

    textBox.Select(textBox.TextLength + 1, 0);
    textBox.SelectedText = textToAppend;
    

    但不应该有理由手动操作。

    (如果你自己反编译它,你会发现它使用了一些可能更有效的内部方法,并且有一个小的特例。)

        2
  •  153
  •   GWLlosa    17 年前

    您可以使用以下代码段:

    myTextBox.SelectionStart = myTextBox.Text.Length;
    myTextBox.ScrollToCaret();
    

    它将自动滚动到最后。

        3
  •  41
  •   Peter Mortensen Pieter Jan Bonestroo    13 年前

    界面似乎已经改变了 .NET method 这实现了上述所有目标。正如Tommy Engebretsen所建议的,将其放入TextChanged事件处理程序中会使其自动执行。

    textBox1.ScrollToEnd();
    
        4
  •  16
  •   GWLlosa    15 年前

    尝试将建议的代码添加到TextChanged事件:

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
      textBox1.SelectionStart = textBox1.Text.Length;
      textBox1.ScrollToCaret();
    }
    
        5
  •  10
  •   Stefan Steiger Marco van de Voort    11 年前
    textBox1.Focus()
    textBox1.SelectionStart = textBox1.Text.Length;
    textBox1.ScrollToCaret();
    

    不适合我(Windows 8.1,无论什么原因)。
    因为我还在.NET2.0上,所以我不能使用ScrollToEnd。

    但这是可行的:

    public class Utils
    {
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        private static extern int SendMessage(System.IntPtr hWnd, int wMsg, System.IntPtr wParam, System.IntPtr lParam);
    
        private const int WM_VSCROLL = 0x115;
        private const int SB_BOTTOM = 7;
    
        /// <summary>
        /// Scrolls the vertical scroll bar of a multi-line text box to the bottom.
        /// </summary>
        /// <param name="tb">The text box to scroll</param>
        public static void ScrollToBottom(System.Windows.Forms.TextBox tb)
        {
            if(System.Environment.OSVersion.Platform != System.PlatformID.Unix)
                 SendMessage(tb.Handle, WM_VSCROLL, new System.IntPtr(SB_BOTTOM), System.IntPtr.Zero);
        }
    
    
    }
    

    VB.NET:

    Public Class Utils
        <System.Runtime.InteropServices.DllImport("user32.dll", CharSet := System.Runtime.InteropServices.CharSet.Auto)> _
        Private Shared Function SendMessage(hWnd As System.IntPtr, wMsg As Integer, wParam As System.IntPtr, lParam As System.IntPtr) As Integer
        End Function
    
        Private Const WM_VSCROLL As Integer = &H115
        Private Const SB_BOTTOM As Integer = 7
    
        ''' <summary>
        ''' Scrolls the vertical scroll bar of a multi-line text box to the bottom.
        ''' </summary>
        ''' <param name="tb">The text box to scroll</param>
        Public Shared Sub ScrollToBottom(tb As System.Windows.Forms.TextBox)
            If System.Environment.OSVersion.Platform <> System.PlatformID.Unix Then
                SendMessage(tb.Handle, WM_VSCROLL, New System.IntPtr(SB_BOTTOM), System.IntPtr.Zero)
            End If
        End Sub
    
    
    End Class
    
        6
  •  9
  •   Tim Cooper    15 年前

    我需要添加一个刷新:

    textBox1.SelectionStart = textBox1.Text.Length;
    textBox1.ScrollToCaret();
    textBox1.Refresh();
    
        7
  •  6
  •   Pete    11 年前

    我发现了一个简单的区别,但在这篇文章中没有提到。

    如果你在做所有的事情 ScrollToCarat() Load() 事件,它不起作用。我刚加了我的名字 ScrollToCarat() Activated() 事件,它运行良好。

    编辑

    Activated 事件被激发(不是在后续激活时),否则它将滚动 每一个 激活表单的时间,这可能是您不想要的。

    激活的() 事件以在程序加载时滚动文本,然后您可以取消订阅事件处理程序本身内的事件,从而:

    Activated -= new System.EventHandler(this.Form1_Activated);
    

    如果每次激活表单时都需要执行其他操作,则可以设置 bool 为了实现你第一次的梦想 激活的() 事件被触发,因此您不必滚动后续激活,但仍可以执行其他需要执行的操作。

    此外,如果您的 TextBox 是在一张账单上,而不是 SelectedTab , ScrollToCarat() 没有效果。因此,在滚动时,您至少需要将其设置为选中的选项卡。您可以将代码包装在 YourTab.SuspendLayout(); YourTab.ResumeLayout(false); 如果在执行此操作时窗体闪烁,则进行配对。

    希望这有帮助!

        8
  •  1
  •   Tom Fuller Terry Jan Reedy    9 年前

    当文本更改时,这将滚动到文本框的末尾,但仍允许用户向上滚动

    outbox.SelectionStart = outbox.Text.Length;
    outbox.ScrollToEnd();
    

        9
  •  1
  •   midoriha_senpai    8 年前

    对于在此处登录并希望看到webforms实现的任何其他人,您希望使用页面请求管理器的endRequest事件处理程序( https://stackoverflow.com/a/1388170/1830512 )。以下是我在母版页的内容页中对文本框所做的操作,请忽略我没有为控件使用变量的事实:

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    
    function EndRequestHandler() {
        if ($get('<%= ((TextBox)StatusWindow.FindControl("StatusTxtBox")).ClientID %>') != null) {
            $get('<%= ((TextBox)StatusWindow.FindControl("StatusTxtBox")).ClientID %>').scrollTop = 
            $get('<%= ((TextBox)StatusWindow.FindControl("StatusTxtBox")).ClientID %>').scrollHeight;
        }
    }
    
    prm.add_endRequest(EndRequestHandler);
    
        10
  •  1
  •   larrycook99    5 年前

    关于Pete关于选项卡上的文本框的评论,我的工作方式是添加

    textBox1.SelectionStart = textBox1.Text.Length;
    textBox1.ScrollToCaret();
    

    到选项卡的布局事件。

        11
  •  1
  •   sam byte    5 年前

    我用这个。简单、干净、快捷!

    txtTCPTxRx.AppendText(newText);
    

    下面是我实际使用的代码

    ThreadSafe(() =>
          {
              string newLog = $"{DateTime.Now:HH:mm:ss:ffff->}{dLog}{Environment.NewLine}";
              txtTCPTxRx.AppendText(newLog);
          });
    
        12
  •  0
  •   TooGeeky    12 年前

    txtSerialLogging->Text=“”;

    txtSerialLogging->附加文本;

    我尝试了上面所有的案例,但问题是在我的案例中,文本s可以减少,增加,也可以在很长一段时间内保持静止。

    所以,当长度(线)保持不变的时候,我在最后面临一个跳线的情况。。。

        13
  •  0
  •   DMike92    11 年前

    private void Log (string s) {
        TB1.AppendText(Environment.NewLine + s);
        TB1.ScrollToCaret();
    }
    
    推荐文章