Search code examples
c#windowswinformskeyboard

Ensure statement is executed only once when a key is pressed and held.


If you press and hold the 5 key on the numpad it will continue to execute a statement in the KeyDown event handler. How can i ensure the statement is executed only once, even if i hold the key down?

Thanks for your attention.

private void form_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
   if (e.KeyCode == Keys.NumPad5)
   {
        dados.enviar("f"); //I want this to run only once!
   }
}

Solution

  • You can set flag on key down and reset it on key up.

        private bool isPressed = false;
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.B && !isPressed )
            {
                isPressed = true;
                // do work
            }
        }
    
        private void Form1_KeyUp(object sender, KeyEventArgs e)
        {
            if (isPressed )
                isPressed = false;
        }