如果没有按下任何键,则不会引发 KeyDown 事件。因此,您的处理程序将不会被调用。
更新(删除循环的选项,因为计时器会为您与睡眠超时的不同线程上的循环相同):
这是带有计时器的示例:
private bool _keyPressed;
private void TimerElapsed(object sender, EventArgs e)
{
if (!_keyPressed)
{
// do what you need
}
}
private void KeyDownHandler(object sender, KeyEventArgs e)
{
_keyPressed = true;
switch (e.KeyCode)
{
// process pressed key
}
_keyPressed = false;
}
更新:我认为在确定是否没有按下任何键之前验证自上次按下键后经过了多少时间是个好主意
private DateTime _lastKeyDownTime;
private const int interval = 100;
private void LoadHandler(object sender, EventArgs e)
{
// start Threading.Timer or some other timer
System.Threading.Timer timer = new System.Threading.Timer(DoSomethingDefault, null, 0, interval);
}
private void DoSomethingDefault(object state)
{
if ((DateTime.Now - _lastKeyDownTime).TotalMilliseconds < interval)
return;
// modify UI via Invoke
}
private void KeyDown(object sender, KeyEventArgs e)
{
_lastKeyDownTime = DateTime.Now;
switch (e.KeyCode)
{
// directly modify UI
}
}