C# Keydown/Keyevents if no key is pressed

3.2k Views Asked by At

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:

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

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

1

There are 1 best solutions below

8
On

If no key pressed, then no KeyDown event raised. 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
    }  
}