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 Regex
s 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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With