Event pressing key 2 times

Asked

Viewed 72 times

0

I have the following event:

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

The result is that every time I press ESC, the form is closed. However, I would like that when pressing once, a method is called to clear the controls and if pressed with ALL the empty controls, he closed the screen.

How can I do that? One if() within this first if (e.KeyValue.Equals(27))? I have to go from field to field checking if they’re equal to "String.Empty"?

  • 1

    Usually the ESC is used to close the screen, even has a property in the form to enable it, no need to encode any key, if you do not think it is better to use a key association?

  • I was interested about this property, but the idea is that once the form was completed, the first ESCclean the screen, instead of closing directly

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

Add to your event Keydown:

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, more can use other controls adding it to the method that cleans and that check following the same logic.

I hope I’ve helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.