Event when key pressed 2 times

0

I have the following event:

    private void TelaAcao_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyValue.Equals(27))
        {
            this.Close();
        }
    }

The result of this is that every time I press ESC , the form is closed. However, I would like you to press once to call a method to clear the controls and press ALL the empty controls to close the screen.

How can I do this? A% of% within this first if() ? Do I have to go from field to field to see if they are equal to " if (e.KeyValue.Equals(27)) "?

    
asked by anonymous 23.03.2018 / 15:29

1 answer

1

A method to check empty control:

bool CheckVazio(Form formulario)
{
     foreach (Control item in formulario.Controls){
          if (item is TextBox && !((TextBox)item).Text.Equals(string.Empty))
               return false
          else if (item is ComboBox && ((ComboBox)item).SelectedIndex > -1)
               return false;
     }

     return true;
}

Method to clear Controls:

void LimparControles(Form formulario)
{
     foreach (Control item in formulario.Controls){
          if (item is TextBox)
              ((TextBox)item).Text = string.Empty;

          else if (item is ComboBox)
              ((ComboBox)item).SelectedIndex = -1;
     }
}

In your KeyDown event add:

private void TelaAcao_KeyDown(object sender, KeyEventArgs e)
{
     if (e.KeyValue.Equals(27))
     {
          if (!CheckVazio((Form)sender))
              LimparControles((Form)sender);
          else
              this.Close();
     }
}

NOTE: As I do not know which controls you use, I used a TextBox and a ComboBox as an example, but you can use other controls by adding it to the clean method and following the same logic.

I hope I have helped!

    
24.03.2018 / 03:11