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

浪子不回头ぞ 提交于 2019-12-23 17:25:21

问题


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

回答1:


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



回答2:


bool alreadyPressed = false;
...

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


来源:https://stackoverflow.com/questions/9251522/ensure-statement-is-executed-only-once-when-a-key-is-pressed-and-held

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!