RichTextBox BeginUpdate() EndUpdate() Extension Methods Not Working

感情迁移 提交于 2019-12-01 02:44:14

问题


I have a richTextBox I am using to perform some syntax highlighting. This is a small editing facility so I have not written a custom syntax highlighter - instead I am using Regexs and updating upon the detection of an input delay using an event handler for the Application.Idle event:

Application.Idle += new EventHandler(Application_Idle);

in the event handler I check for the time the text box has been inactive:

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;
   }
}

But even for relatively small highlights the RichTextBox flickers heavily and it has no richTextBox.BeginUpdate()/EndUpdate() methods. To overcome this I found this answer to a similar dilemma by Hans Passant (Hans Passant has never let me down!):

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; 
} 

However, this gives me odd behaviour upon an update; the cursor dies/freezes and shows nothing but odd looking stripes (see image below).

I clearly can't use an alternative thread to update the UI, so what am I doing wrong here?

Thanks for your time.


回答1:


Try modifying the EndUpdate to also call Invalidate afterwards. The control doesn't know it needs to do some updating, so you need to tell it:

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


来源:https://stackoverflow.com/questions/9418024/richtextbox-beginupdate-endupdate-extension-methods-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!