c#如何判断键盘某个键的双击

文章更新

  1. 20170511-初次成文

为什么会有这篇文章

最近需要判断键盘的双击,网上的找到的都是判断鼠标双击的,所以自己研究了下,分享出来。

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Windows.Forms;
namespace _20170510_doubleclickmonitor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var k_hook = new KeyboardHook();
k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住键按下
k_hook.Start();//安装键盘钩子
}
bool keyBpressed = false;
DateTime firstPressTime;
private void hook_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == (int)Keys.B)
{
//判断是第一次按下还是第二次,根据keyBpressed这个布尔值来判断
if (!keyBpressed)
{
//如果是第一次按下B,不干什么,只记录时间
firstPressTime = DateTime.Now;
//更改keyBpressed的状态
keyBpressed = true;
}
else
{
//如果是第二次按下B
DateTime secondPressTime = DateTime.Now;
var ms = secondPressTime.Subtract(firstPressTime).TotalMilliseconds;
if (ms <= 1000)
{
MessageBox.Show("b pressed twice!first time:"+ firstPressTime + " ;second time:"+ secondPressTime + " span: "+ ms);
keyBpressed = false;
}
else
{
MessageBox.Show("is not fast enough!");
keyBpressed = false;
}
}
}
}
}
}

上面代码的实现,需要键盘监听类KeyboardHook,具体见C#全局键盘监听(Hook)的使用

参考文章

  1. Detect If Certain Key Was Pressed Twice Rapidly
分享到