简体   繁体   中英

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

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;
    }
bool alreadyPressed = false;
...

if (e.KeyCode == Keys.NumPad5 && ! alreadyPressed)
{
    alreadyPressed = true;
    ...

您应该使用IsRepeat标志来检查它是否是第一次按下键。

if (e.KeyCode == Keys.NumPad5 && !e.IsRepeat)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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