简体   繁体   English

C# Keydown/Keyevents 如果没有按键被按下

[英]C# Keydown/Keyevents if no key is pressed

I am programming something right now in c#, trying to "convert" a console application to a windows Forms application and I wanted to do something like the following:我现在正在 c# 中编程,试图将控制台应用程序“转换”为 windows Forms 应用程序,我想执行如下操作:

if("keypress == nokey") 
{
    system.threading.thread.sleep ***
}
while(nokeyispressed) 
{
    system.threading...
}

Basically ask if no key is pressed sleep for some time and this.close();基本上询问是否没有按键被按下 sleep 一段时间和 this.close();

so that if no key is pressed, do something... I just can't get it to work.这样,如果没有按下任何键,就做点什么……我就是无法让它工作。 I would be very greatful for some help..:D我会非常感激一些帮助..:D

If no key pressed, then no KeyDown event raised.如果没有按键按下,则不会引发 KeyDown 事件。 So, your handler will not be called.因此,您的处理程序将不会被调用。

UPDATE (option with loop removed, because timer will make same for you as loop on different thread with sleep timeouts):更新(删除了循环的选项,因为计时器会为您提供与睡眠超时不同线程上的循环相同的功能):

Here is sample with timer:这是带计时器的示例:

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

UPDATE: I think good idea to verify how many time elapsed since last key down before decide if no keys were pressed更新:我认为在决定是否没有按下任何键之前验证自上次按下键以来经过了多少时间是个好主意

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
    }  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM