Thursday, August 10

Updating .NET user controls on the screen

I have some user controls that I need to add a lot of data to. This can be slow as the screen display is updated when each item of data is added. It also makes the dislpay flicker.

I couldn't find an equivalent of the BeginUpdate and EndUpdate functions in .NET 2.0, but it is possible to call the Windows API functions as follows.


private const int WM_SETREDRAW = 11;

[System.Runtime.InteropServices.
DllImport("user32.dll")]
static extern bool SendMessage(IntPtr
hWnd, Int32 msd, Int32 wParam, Int32
lParam);

///
/// Stop updates while we are
/// filling a control with data
///

protected void BeginUpdate()
{
SendMessage(this.Handle, WM_SETREDRAW, 0, 0);
Cursor.Current = Cursors.WaitCursor;
}

///
/// Restart updates
///

protected void EndUpdate()
{
SendMessage(this.Handle, WM_SETREDRAW, 1, 0);
if (Parent != null)
{
Parent.Invalidate(true);
}
Cursor.Current = Cursors.Default;
}


I included these in a base class used by all my user controls, and added code to change the cursor to a wait cursor whilst the control was updating.

No comments: