簡體   English   中英

從左到右和從右到左移動 label

[英]Move the label from left to right and right to left

我的問題很簡單。 我的 Label1 應該從左到右連續移動。 (從表格的左側開始,go 到表格的右側。當它到達表格的右側時,go 到左側,依此類推。)我有 2 個計時器(一個用於右側,一個用於左側) ) 我有下面的代碼,它從左邊開始到右邊,但是當它到達窗體的右邊時,它不會返回。 誰能幫我?

 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();
    }

謝謝。

我認為你把事情復雜化了。 讓我們只有一個計時器,一個步數的像素,我們有時會翻轉為負數,一段時間后又會翻轉回正數。 我們可以通過反復設置左移來移動 label:

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;
    }
}

您可能想對其進行微調,但基本動作就在那里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM