C#:以相反顺序/向上显示richtextbox中的文本
我正在尝试使用 C#.NET 中的 richtextbox 控件创建“日志显示”。
public void logLine(string line)
{
rtxtLoginMessage.AppendText(line + "\r\n");
}
有没有办法以相反的顺序/向上显示文本? (最新的日志和日期将显示在顶部)
非常感谢您的帮助。
I am trying to create a 'log display' using the richtextbox control in C#.NET.
public void logLine(string line)
{
rtxtLoginMessage.AppendText(line + "\r\n");
}
Is there a way to display the text in reverse order/upwards? (where the newest log and date will be displayed at the top)
Your help is much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简答
您想要将选择设置为 0,然后设置
SelectedText
属性。长答案
我是如何解决这个问题的?
使用 Reflector,搜索 RichTextBox 控件并找到
AppendText
方法(遵循基本类型到TextBoxBase
)。看看它做了什么(为了方便起见,在下面)。您将看到它找到结束位置,设置内部选择,然后将
SelectedText
设置为新值。要在开头插入文本,您只需找到开始位置而不是结束位置。现在,每次您想要为文本添加前缀时,您不必重复这段代码,您可以创建一个 扩展方法。
注意:我仅使用
Try/Finally
块来匹配AppendText
的实现。我不确定为什么如果宽度
或高度
为0,我们想要恢复初始选择(如果你知道为什么,请发表评论,因为我有兴趣找出答案)。此外,对于使用“Prepend”作为“Append”的反义词存在一些争议,因为直接的英语定义令人困惑(进行谷歌搜索 - 有几个关于该主题的帖子)。但是,如果您查看巴伦计算机术语词典,它已成为接受使用。
HTH,
丹尼斯
Short Answer
You want to set the selection to 0 and then set the
SelectedText
property.Long Answer
How did I work this out?
Using Reflector, search for the RichTextBox control and find the
AppendText
method (follow the base types toTextBoxBase
). Have a look at what it does (below for convenience).You will see that it finds the end position, sets the internal selection, and then sets the
SelectedText
to the new value. To insert text at the very beginning you simply want to find the start position instead of the end position.Now, so you do not have repeat this piece of code for each time you want to prefix text you can create an Extension Method.
Note: I'm only using the
Try/Finally
block to match the implementation ofAppendText
. I'm not certain as why we would want to restore the initial selection if theWidth
orHeight
is 0 (if you do know why, please leave a comment as I'm interested in finding out).Also, there is some contention to using "Prepend" as the opposite for "Append" as the direct English definition is confusing (do a Google search - there are several posts on the topic). However, if you look at the Barron's Dictionary of Computer Terms it has become an accepted use.
HTH,
Dennis