views:

66

answers:

2

Hey All,

I did quite a bit of searching around and didn't find anything of much help.

Is it possible to "slide" or "move" using C#, an object from one Location to another using a simple For loop?

Thank you

+4  A: 

I would suggest you rather use a Timer. There are other options, but this will be the simplist if you want to avoid threading issues etc.

Using a straight for loop will require that you pump the message queue using Application.DoEvents() to ensure that windows has the opportunity to actually render the updated control otherwise the for loop would run to completion without updating the UI and the control will appear to jump from the source location to the target location.

Here is a QAD sample for animating a button in the Y direction when clicked. This code assumes you put a timer control on the form called animationTimer.

private void button1_Click(object sender, EventArgs e)
{
  if (!animationTimer.Enabled)
  {
    animationTimer.Interval = 10;
    animationTimer.Start();
  }
}

private int _animateDirection = 1;
private void animationTimer_Tick(object sender, EventArgs e)
{
  button1.Location = new Point(button1.Location.X, button1.Location.Y + _animateDirection);

  if (button1.Location.Y == 0 || button1.Location.Y == 100)
  {
    animationTimer.Stop();
    _animateDirection *= -1; // reverse the direction
  }
}
Chris Taylor
Depends on the circumstances of course, but I agree that it seems likely that using a Timer would be useful for whatever he wants to do.
ho1
ooh perfect, thank you :D
lucifer
A: 

Assuming that the object you're talking about is some kind of Control you could just change the Location property of it.

So something like this:

for(int i = 0; i < 100; i++)
{
    ctrl.Location.X += i;
}

Should work I think.

ho1