gpt4 book ai didi

c# - RichTextBox 滚动到结束

转载 作者:太空宇宙 更新时间:2023-11-03 15:01:50 24 4
gpt4 key购买 nike

我有一个 RichTextBox,我想在添加新文本时自动滚动到文本末尾。

这是我的代码:

private void outputWindowTextChanged(object sender, EventArgs e) {
rtb_outputWindow.SelectionStart = rtb_outputWindow.Text.Length;
rtb_outputWindow.ScrollToCaret();
}

我手动将一堆文本添加到 RichTextBox,如下所示:

updateOutputWindow("Lorem ipsum dolor sit amet, ..."); //These strings are really long
updateOutputWindow("Lorem ipsum dolor sit amet, ..."); //I shortened them for this question

结果如下:

screenshot1

在上面的屏幕截图中,您几乎可以看出边缘下方实际上还有更多文本。您还可以查看右侧的滚动条,看到下方还有一点空间。

screenshot2

在上面的屏幕截图中,我使用右侧的滚动条手动向下滚动到底部;显示之前的隐藏文本。

有没有办法确保 RichTextBox 每次都自动滚动到最后?

最佳答案

这改编自 this answer并解决了最后一行有时被截断的问题。

我将答案扩展为 TextBoxBase 上的扩展方法,以便它可以同时用于 TextBoxRichTextBox

用法:

rtb_outputWindow.ScrollToBottom();

实现:

public static class RichTextBoxUtils
{
[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 text box to the bottom.
/// </summary>
/// <param name="tb">The text box base to scroll</param>
public static void ScrollToBottom(this System.Windows.Forms.TextBoxBase tb)
{
if (System.Environment.OSVersion.Platform != System.PlatformID.Unix)
SendMessage(tb.Handle, WM_VSCROLL, new System.IntPtr(SB_BOTTOM), System.IntPtr.Zero);
}

}

关于c# - RichTextBox 滚动到结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45859461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com