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

本文关键字:事件 最简单 方法 是什么 KeyDown Keyboard net | 更新日期: 2023-09-27 17:58:09

我正在.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());
        }
    }
}

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

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

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());
        }
    }
}