gpt4 book ai didi

C#:在不选择文本的情况下更改 WinForm RichTextBox 的字体样式

转载 作者:行者123 更新时间:2023-11-30 17:58:33 25 4
gpt4 key购买 nike

我在我的代码中使用 RichTextBox 来显示语法高亮显示的代码。现在,在每次击键时,我都必须重新解析所有标记并重新为它们重新着色。但是,为 WinForm richtextbox 中的单个单词着色的唯一方法是一个接一个地选择这些单词,然后使用 SelectionFont 为它们着色。

但是如果用户打字速度非常快,我选择单个单词会导致非常明显的闪烁(所选单词具有 Windows 蓝色背景的东西,这会导致闪烁)。有什么办法可以解决这个问题,我可以在不选择单词的情况下为单个单词着色(从而在所选文本周围形成蓝色高亮显示)。我尝试使用 SuspendLayout() 在着色期间禁用渲染,但这没有帮助。提前致谢!

这是我的代码:

代码:

private void editBox_TextChanged(object sender, EventArgs e) {
syntaxHighlightFromRegex();
}

private void syntaxHighlightFromRegex() {
this.editBox.SuspendLayout();

string REG_EX_KEYWORDS = @"\bSELECT\b|\bFROM\b|\bWHERE\b|\bCONTAINS\b|\bIN\b|\bIS\b|\bLIKE\b|\bNONE\b|\bNOT\b|\bNULL\b|\bOR\b";
matchRExpression(this.editBox, REG_EX_KEYWORDS, KeywordsSyntaxHighlightFont, KeywordSyntaxHighlightFontColor);
}

private void matchRExpression(RichTextBox textBox, string regexpression, Font font, Color color) {
System.Text.RegularExpressions.MatchCollection matches = Regex.Matches(this.editBox.Text, regexpression, RegexOptions.IgnoreCase);
foreach (Match match in matches) {
textBox.Select(match.Index, match.Length);
textBox.SelectionColor = color;
textBox.SelectionFont = font;
}
}

在 MyRichTextBox 内部(派生自 RichTextBox):

public void BeginUpdate() {
SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)0, IntPtr.Zero);
}
public void EndUpdate() {
SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);
}
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);
private const int WM_SETREDRAW = 0x0b;

最佳答案

即使看起来您合并了 Hans 的语法高亮文本框,但看起来您并没有使用它。

在突出显示这些单词时,您需要在突出显示之前记住光标所在的位置和长度,因为在您的代码中,您是在四处移动光标而不是将其放回原位。

在不进行错误检查的情况下,尝试将您的代码更改为:

void editBox_TextChanged(object sender, EventArgs e) {
this.editBox.BeginUpdate();
int lastIndex = editBox.SelectionStart;
int lastLength = editBox.SelectionLength;
syntaxHighlightFromRegex();
editBox.Select(lastIndex, lastLength);
this.editBox.SelectionColor = Color.Black;
this.editBox.EndUpdate();
this.editBox.Invalidate();
}

关于C#:在不选择文本的情况下更改 WinForm RichTextBox 的字体样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12150634/

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