开发者

What is the easiest way to capture the Keyboard.KeyDown event in .net

开发者 https://www.devze.com 2023-03-09 07:36 出处:网络
I am developing a Windows Console application in .Net 4.0 C# that analyzes typing patterns. I\'ve added the PresentationCore reference to gain access to System.Windows.Input.Keyboard object.

I am developing a Windows Console application in .Net 4.0 C# that analyzes typing patterns.

I've added the PresentationCore reference to gain access to System.Windows.Input.Keyboard object.

I should stress that I'm not only trying to capture the key pressed开发者_开发问答, I need to calculate the amount of time the key was pressed. That is why I need to access the the KeyDown and KeyUp events.

How do I implement a KeyDown and a KeyUp event handler?

KeyDown events should only be recorded from the context of the application.

This is the code I've tried: (notice I'm stuck at assigning a handler)

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


KeyDown should be sufficient. However you will need to mark the function as static.


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

精彩评论

暂无评论...
验证码 换一张
取 消