CSharp计时器问题

时间:2015-04-22 09:45:00

标签: c# timer intervals

我的计时器无法按预期工作,为什么在每次调用定时器间隔后,pictureBox移动得更快。

我希望在有人按下D按钮后,pictureBox会经常在Form上移动。函数添加和删除事件工作正常,因此不是这样:

    Timer loop;
    Int32 posX, posY;
    public Form1()
    {
        InitializeComponent();
        loop = new Timer();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        sprit.Enabled = false;
        loop.Interval = 10;
        posX = this.sprit.Location.X;
        posY = this.sprit.Location.Y;
    }

    private void nextStep(object sender, EventArgs e)
    {
        posX++;
        this.sprit.Location = new Point(posX, posY);
    }

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyCode) {
            case Keys.D:
                addEvent(nextStep);
                loop.Start();
                break;
        }
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {

        switch (e.KeyCode)
        {
            case Keys.D:
                removeEvent(nextStep);
                loop.Stop();
                break;
        }
    }

1 个答案:

答案 0 :(得分:2)

只要您按住密钥,就会重复调用

Form1_KeyDown,因此您不断致电addEvent(nextStep)

尝试在addEvent(nextStep)

上只调用一次Form1_KeyDown