[英]In c# richtextbox how can i highlight words in a sentence sequentially.
即例如考虑这句话。 “这是我的句子。” 我希望程序先显示突出显示的“ This”,然后显示“ is”,依此类推。 可以实际完成吗? 我应该使用计时器吗? 非常感谢您提供简短的说明。 提前致谢。
如果您不想一直阻止UI,那么计时器是一个不错的选择。 一个非常基本的解决方案是:
将此添加到您的初始化代码:
// index of highlighted text block
var i = 0;
var timer = new Timer()
{
Interval = 300
};
timer.Tick += new EventHandler((sender, e) =>
{
// split the elements to highlight by space character
var textElements = this.richTextBox1.Text
.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)
.ToArray();
// avoid dividing by zero when using modulo operator
if (textElements.Length > 0)
{
// start all over again when the end of text is reached.
i = i % textElements.Length;
// clear the RichTextBox
this.richTextBox1.Text = string.Empty;
for (var n = 0; n < textElements.Length; n++)
{
// now adding each text block again
// choose color depending on the index
this.richTextBox1.AppendText(textElements[n] + ' ', i == n ? Color.Red : Color.Black);
}
// increment the index for the next run
i++;
}
});
timer.Start();
此解决方案使用扩展方法。 要使用此功能,必须添加如下扩展类:
static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox richtTextBox, string text, Color color)
{
richtTextBox.SelectionStart = richtTextBox.TextLength;
richtTextBox.SelectionLength = 0;
richtTextBox.SelectionColor = color;
richtTextBox.AppendText(text);
richtTextBox.SelectionColor = richtTextBox.ForeColor;
}
}
您可以在此处获得有关我使用的扩展方法的更多信息。
该解决方案的缺点是,在突出显示过程中,RichTextBox不能真正使用。 如果希望用户输入一些文本,则应首先停止计时器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.