捕获.net中的Keyboard.KeyDown事件的最简单方法是什么

时间:2011-05-31 18:41:39

标签: c# .net event-handling keyboard-events

我正在开发.Net 4.0 C#中的Windows控制台应用程序,用于分析打字模式。

我添加了PresentationCore引用以获取对System.Windows.Input.Keyboard对象的访问权限。

我应该强调,我不仅要抓住按下的按键,还需要计算按下按键的时间。这就是我需要访问KeyDownKeyUp事件的原因。

如何实现KeyDownKeyUp事件处理程序?

KeyDown事件只应从应用程序的上下文中记录下来。

这是我尝试的代码:(注意我已经坚持分配处理程序)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace TypingBiometrics
{
    class Program
    {
        static void Main(string[] args)
        {           
            Console.WriteLine("Type this sentence");
            Console.ReadLine();

            Keyboard.KeyDownEvent += new KeyboardEventHandler(/*not sure here*/);                
        }

        public void KeyDown(Object sender, KeyboardEventArgs e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

2 个答案:

答案 0 :(得分:0)

KeyDown就足够了。但是,您需要将该函数标记为静态。

答案 1 :(得分:0)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public class Form1 : Form
    {
        DateTime keyDownTime;
        DateTime keyUpTime;


        public Form1()
        {
            this.SuspendLayout();
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Name = "Form1";
            this.Text = "Form1";
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
            this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyUp);
            this.ResumeLayout(false);
        }

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

        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            keyUpTime = DateTime.Now;

            MessageBox.Show((keyUpTime.Subtract(keyDownTime)).TotalSeconds.ToString());
        }
    }
}