Home > Enterprise >  Move the label from left to right and right to left
Move the label from left to right and right to left

Time:12-15

My question is very simple. My Label1 should move continuously from left to right. (Start from the left part of the form and go to the right part of the form. When it reaches the right part of the Form, go to the left and so on.) I have 2 timers(one for right and one for left) I have the following code, it starts at the left and goes to the right, but when it reaches the right of the Form, it doesn't return. Can anyone help me?

 enum Position
    {
        Left,Right
    }
    System.Windows.Forms.Timer timerfirst = new System.Windows.Forms.Timer();

    private int _x;
    private int _y;
    private Position _objPosition;
  public Form1()
    {
        InitializeComponent();            
        if (label1.Location == new Point(0,180))
        {
            _objPosition = Position.Right;
        }
        if (label1.Location == new Point(690,0))
        {
            _objPosition = Position.Left;
        }                         
    }
private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Label1.SetBounds(_x, _y, 0, 180);
    }

private void tmrMoving_Tick(object sender, EventArgs e)
    {
        tmrMoving.Start();

        if (_objPosition == Position.Right && _x < 710)
        {   
          _x  =10;          
        }
       
        if(_x == 710)
        {
            tmrMoving.Stop();
        }
    Invalidate();
    }

private void tmrMoving2_Tick(object sender, EventArgs e)
    {
        tmrMoving2.Start();
        if (_objPosition == Position.Right && _x > 690)
        {
            _x -= 10;
        }
        if(_x == 1)
        {
            tmrMoving2.Stop();
        }
        Invalidate();
    }

Thanks.

CodePudding user response:

I think you've overcomplicated things. Let's just have one timer, a step number of pixels that we sometimes flip negative, and some time later flip back to positive. We can move the label by repeatedly setting its Left:

public partial class Form1 : Form
{
    private int _step = 10;

    public Form1()
    {
        InitializeComponent();

    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (label1.Right > this.Width) _step = -10;
        if (label1.Left < 0) _step = 10;
        label1.Left  = _step;
    }
}

You might want to fine tune it, but the basic motion is there

  • Related