gpt4 book ai didi

c# - 在 C# 中为 RichTextBox 中的所有事件着色的更快方法

转载 作者:行者123 更新时间:2023-11-30 17:20:59 24 4
gpt4 key购买 nike

我有一个 RichTextBox,指定的搜索字符串大约出现了 1000 多次。

我使用以下函数为所有事件着色:

public void ColorAll(string s)
{
rtbxContent.BeginUpdate();

int start = 0, current = 0;
RichTextBoxFinds options = RichTextBoxFinds.MatchCase;
start = rtbxContent.Find(s, start, options);
while (start >= 0)
{
rtbxContent.SelectionStart = start;
rtbxContent.SelectionLength = s.Length;
rtbxContent.SelectionColor = Color.Red;
rtbxContent.SelectionBackColor = Color.Yellow;

current = start + s.Length;
if (current < rtbxContent.TextLength)
start = rtbxContent.Find(s, current, options);
else
break;
}

rtbxContent.EndUpdate();
}

但是我发现它很慢。

但是,如果我对同一文本中出现次数较少的另一个词的所有出现进行着色,我发现它非常快。

所以我猜缓慢的原因是(这两行可能涉及 UI 刷新):

    rtbxContent.SelectionColor     = Color.Red;
rtbxContent.SelectionBackColor = Color.Yellow;

有没有更快的方法做同样的工作,比如我在内存中着色,然后一次性显示结果?

我表达清楚了吗?

谢谢。

最佳答案

有一个更快的方法。

使用正则表达式查找匹配项然后在富文本框中突出显示

    if (this.tBoxFind.Text.Length > 0)
{
try
{
this.richTBox.SuspendLayout();
this.Cursor = Cursors.WaitCursor;

string s = this.richTBox.Text;
System.Text.RegularExpressions.MatchCollection mColl = System.Text.RegularExpressions.Regex.Matches(s, this.tBoxFind.Text);

foreach (System.Text.RegularExpressions.Match g in mColl)
{
this.richTBox.SelectionColor = Color.White;
this.richTBox.SelectionBackColor = Color.Blue;

this.richTBox.Select(g.Index, g.Length);
}
}
finally
{
this.richTBox.ResumeLayout();
this.Cursor = Cursors.Default;
}
}

关于c# - 在 C# 中为 RichTextBox 中的所有事件着色的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3849261/

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