I have a piano in which when I press a button, a certain sound is played.
How to make it so that when you press and hold on a key, button1.PerformClick(); It worked 1 time and the sound did not repeat.

 private void Form1_KeyDown(Object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.D1: button1.PerformClick(); button1.BackColor = System.Drawing.Color.Gray; label3.Text = "До / 1"; label5.Text = "1"; break; } } 

    2 answers 2

    Store the bool isPressed variable in class. In the Form1_KeyDown method Form1_KeyDown set it to true ; in the Form1_KeyUp method, Form1_KeyUp to false . Check if the button is pressed in the Form1_KeyDown method via if(!isPressed){...}

    • Thanks, earned - Valentin

    You can try to disable auto-repeat in the keyboard settings.

    Or decide at the program level, set the flag of pressing, and if it is set, ignore the keydown of the key pressed until its KeyUp occurs. However, there is a danger that the release will be lost - the keyboards have a limit on the number of simultaneously pressed keys, above which the following events are ignored. Yes, and for other reasons, the event may be lost.