【发布时间】:2012-02-24 01:51:41
【问题描述】:
我有一个richTextBox,用于执行一些语法高亮。这是一个小型编辑工具,因此我没有编写自定义语法荧光笔 - 相反,我使用 Regexs 并使用 Application.Idle 事件的事件处理程序在检测到输入延迟时进行更新:
Application.Idle += new EventHandler(Application_Idle);
在事件处理程序中,我检查文本框处于非活动状态的时间:
private void Application_Idle(object sender, EventArgs e)
{
// Get time since last syntax update.
double timeRtb1 = DateTime.Now.Subtract(_lastChangeRtb1).TotalMilliseconds;
// If required highlight syntax.
if (timeRtb1 > MINIMUM_UPDATE_DELAY)
{
HighlightSyntax(ref richTextBox1);
_lastChangeRtb1 = DateTime.MaxValue;
}
}
但即使是相对较小的亮点,RichTextBox 也会严重闪烁,并且它没有 richTextBox.BeginUpdate()/EndUpdate() 方法。为了克服这个问题,我找到了this answer to a similar dilemma by Hans Passant(Hans Passant 从来没有让我失望过!):
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class 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;
}
但是,这让我在更新时出现奇怪的行为;光标消失/冻结,只显示奇怪的条纹(见下图)。
我显然不能使用替代线程来更新 UI,所以我在这里做错了什么?
感谢您的宝贵时间。
【问题讨论】:
标签: c# .net extension-methods richtextbox