测量keydown和keyup事件之间的时间

时间:2015-11-04 00:03:58

标签: c# c#-4.0

我正在尝试捕获KeyDownKeyUp之间的时间,以毫秒为单位,每个类型字符的两个事件之间经过的时间,我使用Stopwatch.GetTimestamp(),因为我需要获取一个高分辨率的时间戳,如下面的编码所示,我想知道这是否是以毫秒为单位得到时间的正确公式:

int timeStampInMiliseconds = Convert.ToInt32(elapsedTicks * 1000000 / Stopwatch.Frequency);以毫秒为单位获取时间。

由于时间结果没有显示任何一致性,并且在这两个事件之间可能达到5秒,这是不现实的!

public partial class Form1 : Form
{
    long timeStamp;
    long initialTimeStamp;


    public Form1()
    {

        InitializeComponent();
        Stopwatch stopWatch = new Stopwatch();
         // Uses the second Core or Processor for the Test
        // Prevents "Normal" processes from interrupting Threads
        // Prevents "Normal" Threads  
        initialize();

    }

    public void initialize()
    {
        //
    }

    public void textBox1_KeyDown(object sender, KeyEventArgs e)
    {

        initialTimeStamp = Stopwatch.GetTimestamp();
    }

    public void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        timeStamp = Stopwatch.GetTimestamp();

        long elapsedTicks = timeStamp  -initialTimeStamp;

        int timeStampInMiliseconds = Convert.ToInt32(elapsedTicks * 1000000 / Stopwatch.Frequency);
    }
}

真的很感谢你的帮助。

2 个答案:

答案 0 :(得分:3)

更好的方法是使用StopWatch.ElapsedMilliseconds属性。

textBox1_KeyDown事件处理程序中,只需重新启动秒表:

stopWatch.Restart();

textBox1_KeyUp事件处理程序中,请阅读ElapsedMilliseconds属性,如下所示:

long timeStampInMiliseconds = stopWatch.ElapsedMilliseconds;

您还需要使stopWatch像这样的实例变量:

public partial class Form1 : Form
{
    long timeStamp;
    long initialTimeStamp;
    Stopwatch stopWatch;

    public Form1()
    {

        InitializeComponent();
        stopWatch = new Stopwatch();

        ....

    }
    ....
}

答案 1 :(得分:0)

您不需要使用Stopwatch。使用以下内容更容易获得时间戳:

long t = DateTime.Now.Ticks;

试试这个:

public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    initialTimeStamp = DateTime.Now.Ticks;
}

public void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    timeStamp = DateTime.Now.Ticks;

    long elapsedTicks = timeStamp - initialTimeStamp;

    long timeStampInNanoseconds = elapsedTicks * 100;
}

我在纳秒内做了更准确的事情,但如果你愿意,你可以转换为毫秒:

long timeStampInMiliseconds = elapsedTicks / 10000;