.net 2010 calling DoEvents (yes I want to) from inside a custom control library

vulkanino picture vulkanino · Sep 21, 2010 · Viewed 12.4k times · Source

I have a custom control's library. Now there's a control which looks like a panel, and when it opens up I want to animate its vertical growing like this:

For h As Single = 0 To finalHeight Step 0.5
    Me.Height = CInt(h)
    '  HERE I WANT TO CALL DoEvents'
Next
Me.Height = finalHeight 

If I don't call DoEvents in the loop then the animation is not shown, I only get the final height without a visual feedback along the way.

I can call DoEvents from inside my main WinForm project, but can't inside a library.

How can I do that, without drowning into the deep threads waters?

Answer

Hans Passant picture Hans Passant · Sep 21, 2010

Sorry, but it is completely impossible to make using DoEvents safe here. Nothing good is going to happen when the user closes the form while your animation is going. It will crash the program with an ObjectDisposed exception. Making DoEvents safe requires setting the form's Enabled property to false so that the user cannot accidentally cause mishaps like this. A control can not reasonable set the form's Enabled property to false, especially not for an animation.

The workaround is simple enough, just use a Timer with an Interval of 15 msec. Plenty fast enough to make the animation look smooth. You'll find sample code that does this in my answer in this thread.