我有一个文本框的. multiline属性设置为true。每隔一段时间,我都会向它添加新的文本行。我希望文本框自动滚动到最底部的条目(最新的一个)每当添加一个新的行。我该怎么做呢?
当前回答
关于皮特关于一个标签上的文本框的评论,我得到的工作方式是添加
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();
到选项卡的Layout事件。
其他回答
这只对我有用……
txtserialloging ->Text = "";
txtSerialLogging->AppendText(s);
我尝试了上面所有的情况,但问题是,在我的情况下,文本可以减少,增加,也可以长时间保持静态。 静态的意思是,静态的长度(线条)但内容不同。
所以,当长度(行)在一段时间内保持不变时,我在最后面临一个行跳转的情况……
您可以使用以下代码片段:
myTextBox.SelectionStart = myTextBox.Text.Length;
myTextBox.ScrollToCaret();
它会自动滚动到最后。
当文本被更改时,这将滚动到文本框的末尾,但仍然允许用户向上滚动
outbox.SelectionStart = outbox.Text.Length;
outbox.ScrollToEnd();
在Visual Studio Enterprise 2017上测试
textBox1.Focus()
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();
对我不起作用(Windows 8.1,不管是什么原因)。 由于我仍然使用。net 2.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
我用这个。简单、干净、快捷!
txtTCPTxRx.AppendText(newText);
下面是我使用的实际代码
ThreadSafe(() =>
{
string newLog = $"{DateTime.Now:HH:mm:ss:ffff->}{dLog}{Environment.NewLine}";
txtTCPTxRx.AppendText(newLog);
});
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 检测涡旋方向
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?