0

I want to build a simple C# Windows Form Application that gathers user's keystrokes data.

Basically, the user needs to type in a word with length 10. I want to record each key's holding time, keydown to keydown time and keyup and keydown for adjacent keystrokes (so there are 10 + 9 + 9 = 28 measurements).

Could anyone tell me how to capture this information using text box events?

Thanks in advance

Nikolai Samteladze
  • 7,699
  • 6
  • 44
  • 70
Freya Ren
  • 2,086
  • 6
  • 29
  • 39

1 Answers1

4

You can handle KeyUp and KeyDown events on your TextBox. You can get current timestamp using DateTime.Now.

Store your last KeyUp and KeyDown events time and add measurements like this:

private DateTime? keyUpTime = null;
private DateTime? keyDownTime = null;

private List<double> keyDownKeyUpMeasurements = new List<double>();
private List<double> keyDownKeyDownMeasurements = new List<double>();
private List<double> keyUpKeyDownMeasurements = new List<double>();

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    DateTime prevKeyDownTime = keyDownTime;
    keyDownTime = DateTime.Now;

    if (prevKeyDownTime != null)
    {
        keyDownKeyDownMeasurements
            .Add(keyDownTime.Subtract(prevKeyDownTime).TotalMilliseconds);
    }

    if (keyUpTime != null)
    {
        keyUpKeyDownMeasurements
            .Add(keyDownTime.Subtract(keyUpTime).TotalMilliseconds);
    }
}

private void textBox_KeyUp(object sender, KeyEventArgs e)
{
    keyUpTime = DateTime.Now;
    keyDownKeyUpMeasurements
        .Add(keyUpTime.Subtract(keyDownTime).TotalMilliseconds);
}
Nikolai Samteladze
  • 7,699
  • 6
  • 44
  • 70
  • Thanks, I think it can work. I'm trying to ignore bad input. Do you know how to use KeyEventArgs.KeyValue? Is "string ch = ((Char)e.KeyCode).ToString()" correct? – Freya Ren Nov 25 '13 at 04:46
  • I doubt that cast `(Char)e.KeyCode` will work. `KeyCode` returns `Keys` enum value. What are you trying to achieve? To filter specific characters you can use something like `e.KeyCode != Keys.A`. – Nikolai Samteladze Nov 25 '13 at 04:54
  • The user's input should be a fixed words with length of 10 (like "abcdefghij"). So that I need to check whether the user press the right key. I don't want to use a long condition like if(e.KeyCode!=keys.A && e.KeyCode!=Keys.B &&......) – Freya Ren Nov 25 '13 at 05:05
  • You can use something like `bool stringIsAllLetters = yourString.All(c => Char.IsLetter(c));`. – Nikolai Samteladze Nov 25 '13 at 05:16