Friday, September 5, 2008

C#: Reducing Flicker

C#: Reducing Flicker

Some professional C# and Visual Basic developers have been making suggestions that tell me that this isn't as obvious as I had thought. One suggestion that certainly reduces the flicker--as well as teaching me something that I needed to know--was to use a timer to drive the refresh. Instead of hooking up event handlers for just about every possible mouse event, instead:

Timer Clock;

public Form1()
{
// Set up a two second timer to force refresh.
Clock = new Timer();
Clock.Interval = 2000;
Clock.Start();
Clock.Tick += new EventHandler(Timer_Tick);
}

public void Timer_Tick(object sender, EventArgs eArgs)
{
if (sender == Clock)
{
System.Console.WriteLine("tick...");
this.Invalidate();
}
}

And then disable the various this.Invalidate() calls for the event handlers for mouse movement, mouse up, and so on. Obviously, if the interval between refreshes is very short, you still get the flicker, but it is at least a consistent flicker. (Is that a virtue? Well, it's less distracting than the random timing flicker that comes when you move the mouse around.) At three seconds, it is slow enough to be annoying, because you can see it taking time to do the refresh. At two seconds, you sometimes notice that the image hasn't refreshed, and sometimes you don't.

But then I pulled back for a second, thought about it, and realized that I was doing this all wrong! The real problem is that when I perform operations that cause, or could cause, a change in the data, that's when I need to call this.Invalidate() to force a refresh. So I've removed all the funny event handlers, and it now is flicker free, and simpler! I'm updating the listing and the code shortly.

No comments:

Post a Comment