如何使用计时器使文本左右移动

本文关键字:左右 移动 文本 何使用 计时器 | 更新日期: 2023-09-27 18:24:24

我有一个标签,我正试图将其左右移动。我让它使用while(true)循环,但决定尝试使用计时器。

    private int x = 0;
    private int y = 11;
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (x <= 11)
        {
            x++;
            string ping = new string(' ', x) + "ping";
            label2.Text = ping;
        }
        else if (y >= 0)
        {
            y--;
            string pong = new string(' ', y) + "pong"; // this is where the exceptions given
            label2.Text = pong;
        }

就我所知,它在某种程度上是有效的,但在它完成之后,一旦它抛出异常

"count"必须为非负数。

我不知道如何解决这个问题,任何帮助都会很好。

如何使用计时器使文本左右移动

y达到0时,它仍将再次递减。更改为y > 0,您应该没事。

string()构造函数在将负值作为第二个参数传递时抛出。

MSDN:字符串构造函数(Char,Int32)

ArgumentOutOfRangeException-计数小于零。

所以只要改变

if (y >= 0)

if (y > 0)
private int x = 0;
private int y = 100;
private void timer1_Tick(object sender, EventArgs e)
{
    if (x <= 100)
    {
        x++;
        string ping = new string(' ', x) + "COURT DOCUMENT MANAGEMENT SYSTEM";
        label1.Text = ping;
    }
    else if (y > 0)
    {
        y--;
        string pong = new string(' ', y) + "MY ARCHIVE MY LIFELINE!!!!"; // this is where the exceptions given
        label2.Text = pong;
    }
}
if (x <= 11)
{
    x++;
    string ping = new string(' ', x) + "ping";
    label2.Text = ping;
    if (x == 11)
    {
        y = 11;
    }
}
else if (y >= 0)
{
    y--;
    string pong = new string(' ', y) + "pong"; // this is where the exceptions given
    label2.Text = pong;
    if (y == 0)
    {
        x = 0;
    }
}