C#Timer没有从一次点击重置到另一次

时间:2013-12-14 00:06:11

标签: c# timer

我需要用Ticks存储钢琴的持续时间,然后根据持续时间制作音乐笔记(音乐播放器会知道)。

我使用100的间隔,但是对于某些测试我在1000使用它。

问题是这个。当我调用该方法时(我将 1000毫秒间隔一次),计时器启动..如果我没有设法得到1000毫秒它显示持续时间0:但是然后,如果我做2秒,它显示3秒,如果我尝试再按一秒钟(一个不同的键),它将显示4秒而不是1。

它一直在重复出现。同样的情况发生在100间隔期间。它发疯了。有时40有时23等等。知道如何修复(重置计时器)

N.B我使用System.Windows.Forms.Timer 作为库

调用下面进一步方法的方法的一部分

for (int i = 0; i < 15; i++)
{
    WhiteKey wk = new WhiteKey(wKeys[i], wPos[i]-35,0); //create a new white Key with [i] Pitch, at that x position and at y =0 position
    wk.MouseDown += onRightClick; //holds the Duration on Right Click
    wk.MouseUp += onMouseUp;
    wk.Click += new EventHandler(KeyClick); //Go to KeyClick Method whenever a key is pressed
    this.panel1.Controls.Add(wk); //Give it control (to play and edit)
}

控制时间的方法

private void onRightClick(object sender, MouseEventArgs e)
{        
    wk = sender as WhiteKey;
    duration = 0;
    t1.Enabled = true;
    t1.Tick += timeTick;
    t1.Interval = 100; 
}

private void timeTick(object sender, EventArgs e)
{
    duration++;
}

private void onMouseUp (object sender, MouseEventArgs e)
{

    t1.Enabled = false;
    String time = "Key: " + pitch + "\nDuration: " +duration ; //Test purposes to see if timer works
    MessageBox.Show(time);
}

2 个答案:

答案 0 :(得分:1)

您正在尝试测量时间,请勿使用计时器,请使用Stopwatch

您可以找到C# Stopwatch Exmples at dotnetpearls.com

在摘要中,你想要做的就是这样:

private void onRightClick(object sender, MouseEventArgs e)
{
    stopwatch.Reset();
    stopwatch.Start();
}

private void onMouseUp (object sender, MouseEventArgs e)
{
    stopwatch.Stop();
    String msg = "Duration in seconds: " + (stopwatch.ElapsedMilliseconds / 1000.0).ToString("0.00");
    MessageBox.Show(msg);
}

注意:您可能想要更改单位或字符串格式。


使用计时器的注意事项:

1)System.Windows.Forms.Timer使用窗口的消息循环,这意味着它可能会因为窗口忙于处理其他事件(例如单击)而延迟。为了更好的行为,请使用System.Threading.Timer

2)如果使用System.Windows.Forms.Timer,请不要每次单击设置Tick事件处理程序。每次添加时,事件处理程序都会执行一次。

那是:

private void onRightClick(object sender, MouseEventArgs e)
{        
    wk = sender as WhiteKey;
    duration = 0;
    t1.Enabled = true;
    //t1.Tick += timeTick; you should add this only once not each click
    t1.Interval = 100;
}

3)如果您使用System.Threading.Timer,您可能想要变量duration volatile

答案 1 :(得分:1)

t1.Tick += timeTick;

顺便提一下,在代码示例中,每次单击鼠标右键都会订阅“Tick”计时器事件。 所以如果你单击2次

private void timeTick(object sender, EventArgs e)

方法将被调用两次,'duration ++'将被执行两次。您的事件订阅代码只应为计时器执行一次。 附:如果你需要测量持续时间,Timer不是最好的方法。