Gad
Gad

Reputation: 42306

What is the best way to do a flicker-free animated C# custom control?

I am currently creating a custom control that needs to handle animation in a C# project. It is basically a listbox that contains a fixed number of elements that are subject to move. An element (another user control with a background image and a couple of generated labels) can move upwards, downwards or be taken out of the list.

I would like to create animated movement as the elements get moved around within the container custom control but it seems to me that moving controls around using lines such as

myCustomControl.left -= m_iSpeed;

triggered within a timer event is flickery and has a terrible rendering, even with double buffering turned on.

So here's the question : What is the best way to achieve a flicker-free animated C# control? Should I just not create custom controls and handle all of the drawing within a panel's background image that I generate? Is there a super animation method that I have not discovered? :)

Thanks!

Upvotes: 4

Views: 8155

Answers (4)

Mark Heath
Mark Heath

Reputation: 49482

your best bet for flicker-free animation is to do the painting yourself (use the Graphics object in the Paint event handler) and use double-buffering. In your custom control you will need code like this in the constructor:

this.SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | 
    ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor,
    true);

Upvotes: 3

Lou Franco
Lou Franco

Reputation: 89152

The normal way to get flicker-free animation is to implement double-buffering. Take a look at this Code Project article

http://www.codeproject.com/KB/GDI-plus/flickerFreeDrawing.aspx

Minimizing calls to paint until you are ready is also a good idea.

Upvotes: 0

FryHard
FryHard

Reputation: 10475

A similar discussion took place this morning on this question. visual c# form update results in flickering. so I will be lazy and give the same answer I gave there:

You could try to call this.SuspendLayout(); before you start your move and this.ResumeLayout(false); when you have finished moving all of the controls. In this way all controls should draw at once and you should have less of a flicker.

On a side note I have tried to reproduce this here at work, but seem to be failing. Can you give some more sample code that I can fix maybe?

Upvotes: 1

Related Questions