C#:以相反的顺序/向上显示richtextbox中的文本

abr*_*pin 2 c# reverse rtf richtextbox

我正在尝试使用C#.NET中的richtextbox控件创建"日志显示".

public void logLine(string line)
{
     rtxtLoginMessage.AppendText(line + "\r\n");
} 
Run Code Online (Sandbox Code Playgroud)

有没有办法以反向/向上显示文本?(最新的日志和日期将显示在顶部)

非常感谢您的帮助.

Den*_*nis 9

简答

您想将选择设置为0,然后设置SelectedText属性.

public void logLine(string line)
{
    rtxtLoginMessage.Select(0, 0);    
    rtxtLoginMessage.SelectedText = line + Environment.NewLine;
} 
Run Code Online (Sandbox Code Playgroud)

答案很长

我是怎么解决这个问题的?

使用Reflector,搜索RichTextBox控件并找到AppendText方法(遵循基类型TextBoxBase).看看它做了什么(下面是为了方便起见).

public void AppendText(string text)
{
    if (text.Length > 0)
    {
        int num;
        int num2;
        this.GetSelectionStartAndLength(out num, out num2);
        try
        {
            int endPosition = this.GetEndPosition();
            this.SelectInternal(endPosition, endPosition, endPosition);
            this.SelectedText = text;
        }
        finally
        {
            if ((base.Width == 0) || (base.Height == 0))
            {
                this.Select(num, num2);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您将看到它找到结束位置,设置内部选择,然后将其SelectedText设置为新值.要在最开始插入文本,您只需要找到起始位置而不是结束位置.

现在,所以每次想要为文本添加前缀时都没有重复这段代码,您可以创建一个扩展方法.

public static void PrependText(this TextBoxBase textBox, string text)
{
    if (text.Length > 0)
    {
        var start = textBox.SelectionStart;
        var length = textBox.SelectionLength;

        try
        {
            textBox.Select(0, 0);
            textBox.SelectedText = text;
        }
        finally
        {
            if (textBox.Width == 0 || textBox.Height == 0)
                textBox.Select(start, length);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我只使用Try/Finally块来匹配实现AppendText.我不确定为什么我们想要恢复初始选择,如果WidthHeight为0(如果你知道为什么,请留下评论,因为我有兴趣找到).

此外,还有一些争论使用"Prepend"作为"附加"的反面,因为直接的英语定义令人困惑(进行Google搜索 - 该主题有几篇帖子).但是,如果你看看巴伦的计算机术语词典,它已成为一种公认的用途.

HTH,

丹尼斯