Capture key pressed using name instead of numbers

Asked

Viewed 21 times

1

I’m trying to capture the value of each key in C# by the Keydown event, works perfectly, but the value of each is returned by numbers, for example when pressing TAB is captured 9.

There would be a way to get the value of the key by name, without using multiple ifs?

  private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        string teclaDigitada = Convert.ToString(e.KeyValue);
        label1.Text = teclaDigitada;

        if (teclaDigitada == "38") { label2.Text = "SETA-CIMA"; }
        if (teclaDigitada == "40") { label2.Text = "SETA-BAIXO"; }
        if (teclaDigitada == "37") { label2.Text = "SETA-ESQUERDA"; }
        if (teclaDigitada == "39") { label2.Text = "SETA-DIREITA"; }
        if (teclaDigitada == "9") { label2.Text = "TAB"; }
        if (teclaDigitada == "20") { label2.Text = "CAPS LOOK"; }
        if (teclaDigitada == "16") { label2.Text = "SHIFT"; }
        if (teclaDigitada == "17") { label2.Text = "CTRL"; }
        if (teclaDigitada == "91") { label2.Text = "WINDOWS"; }
        if (teclaDigitada == "18") { label2.Text = "ALT"; }
    }

1 answer

1

Using codes is the best option, because, how would the description be? I would need to do this for each language, etc.

But to help, there is one emum associated with Keyvalues, that helped to make the code more readable, for example:

if (e.KeyValue == Key.F)

You can use this enum and pick up his "description" by converting to string, but as I mentioned above, will use the names in the language that was defined and with the nomenclature that he has, but if this is not a problem, can help to remove these heaps of if:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    // converte para o enum (Keys)
    var keyEnum = (Keys)e.KeyValue;
    // converte para string, pegando o "nome" do enum, como Ctrl, Shift, A, B, etc
    label1.Text = keyEnum.ToString();
}

Browser other questions tagged

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