tags:

views:

340

answers:

2

Hi,

I'm trying to move a picturebox in a containing control by changing its Top and Left properties every 20ms. On a black background it's a bit smoother but when assigning a BackgroundImage to the control, the picturebox leaves a trail behind it until the control is redrawn a few seconds later, slows down abruptly then launches forward, or moves in a jagged trajectory.

I think when the PictureBox control is redrawn, the thread that changes its left and top properties is halted until redrawn is complete and that causes it to queue up any iterations of the timer loop that were held up, when the redraw is complete.

Is there anyway to smoothen up the picturebox's movement?

Thanks F

+2  A: 

I don't know exactly how to resolve the problem (other than switching to WPF) but I can say the lag you're getting is coming from the invalidation of the areas that are being updated as you move the PictureBox. What you want to do is somehow back-buffer the new position and switch to the buffer, rather than relying on GDI to do the redraw in realtime. HTH.

Dave Swersky
+3  A: 

I'd suggest drawing an image in one control as opposed to moving around controls.

Create a custom control, override OnPaint and draw your "picture box" inside there. If you do this you can also back buffer. Do this by calling Graphics.FromImage() to create a graphics object from an image. Paint onto that and finally call g.DrawImage on the REAL graphics object (in the eventArgs) once you're done drawing.

Quibblesome
That seems to have helped with the trail and the jagged motion. Yet, I'm still stuck with the problem of the Bitmap staying stationary for a second or two, after it traverses a few inches.
FrancisCastiglione
Is there an errent Application.DoEvents() in your code? That would explain such a delay. If you're not using that then I wonder what could be causing the problem. Can you extract it into a small but complete example?
Quibblesome
Might I mention that the movement is now clear and not jiggery but only if the custom control runs in its own separate application. The big application i want to run it in has another timer and does some other things too so something else is taking over in the meantime. I'll try running the movement in a thread and if that doesn't work I'll get back to you on this. Thanks.
FrancisCastiglione
Well you really want to keep your threads to a minimum with GDI+ as it is a single threaded graphics library.
Quibblesome
Also doublecheck with your "main app" that you're not using Windows.Forms.Timers where you could be using System.Threading.Timers. A callback in a Windws.Forms.Timer will be using the UI thread, if it is touching controls this is neccessary if it is not though then it is wasting precious UI resources.
Quibblesome