0

我需要监控用户在键入时按住每个键的时间。到目前为止,我已经使用了一个 keyBoard 事件处理程序,并在 e.KeyDown 处启动了秒表,并在 e.KeyUp 处停止了它。在用户同时按住两个按钮之前,这可以正常工作,例如在大写时按住 shift 键。我的代码:

 public partial class LoginPage : Form
    {
        public LoginPage()
        {
            InitializeComponent();
        }

        Stopwatch KeyStopWatch = new Stopwatch();
        Stopwatch KeyStopWatch2 = new Stopwatch();

        private void textBoxUsername_KeyDown(object sender, KeyEventArgs e)
        {
            KeyStopWatch.Start();

        }


        private void textBoxUsername_KeyUp(object sender, KeyEventArgs e)
        {

            KeyStopWatch.Stop();


            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Desktop\KeyTimes.txt", true))
            {

                file.Write(e.KeyCode + " ");
                file.WriteLine(KeyStopWatch.ElapsedMilliseconds);

            }

            KeyStopWatch.Reset();
            KeyStopWatch2.Reset();
        }
    }

这是我得到的示例输出,一个没有大写,另一个没有,顺便说一句,两者都有错误

T 153
H 0
I 89
S 89
Space 111
I 73
S 105
Space 126
A 121
Space 132
T 253
S 0
E 0
T 116

Space 95

T 248
ShiftKey 0
H 89
I 95
S 89
Space 111
I 116
S 100
Space 126
A 111
Space 122
T 407
ShiftKey 0
E 185
S 132
T 84

我的问题; 有没有办法在不为每个特定键编写事件的情况下有效地跟踪每个键的时间?

编辑:我想说的是,如果同时按下,是否可以独立跟踪两个键的时间

4

1 回答 1

1

我不确定我是否理解您的问题,但我会使用 aDictionary<Keys, Stopwatch>来跟踪时间。作为字典的键,我会使用每个按键的小写字符。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private readonly Dictionary<Keys, Stopwatch> _stopwatches = new Dictionary<Keys, Stopwatch>();

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        _stopwatches[e.KeyCode] = Stopwatch.StartNew();
    }

    private void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        textBox2.Text += e.KeyCode;

        Stopwatch stopwatch;
        if (_stopwatches.TryGetValue(e.KeyCode, out stopwatch))
        {
            stopwatch.Stop();
            textBox2.Text += " " + stopwatch.ElapsedMilliseconds + "ms";
        }

        textBox2.Text += Environment.NewLine;
    }
}

textBox1 是输入框。textBox2 是输出框,但您也可以在此处使用文本文件。

于 2013-09-18T19:06:20.323 回答