【问题标题】:RichTextBox BeginUpdate() EndUpdate() Extension Methods Not WorkingRichTextBox BeginUpdate() EndUpdate() 扩展方法不起作用
【发布时间】: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


    【解决方案1】:

    尝试修改 EndUpdate 以在之后也调用 Invalidate。控件不知道它需要做一些更新,所以你需要告诉它:

    public void EndUpdate() 
    { 
      SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);  
      this.Invalidate();
    }
    

    【讨论】:

    • 那是薄荷!工作就像一个魅力......一个小问题,你如何了解扩展方法及其微妙之处? SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero); 不完全是标准 C#!?还是这样?
    • @Killercam SendMessage 和扩展是两个不同的东西。 SendMessage 正在调用 Windows API 函数。对于扩展,请参阅Extension Methods (C# Programming Guide)
    • 感谢您的回复。我意识到两者是不同的。感谢您的链接和您的帮助,非常感谢。
    猜你喜欢
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多