C# Compare the Key Pressed on the Keyboard

1.2k Views Asked by At

I have a textbox and a button.I'm saving the value(keyboard key) entered in the TextBox.I need to give a message when I press the right keyboard key.

private void btn_Click(object sender, EventArgs e)
{
    Properties.Settings.Default.text1 = text1.Text;
    Properties.Settings.Default.Save();
}

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyData == text1.Text) //--------->> error
    {
        MessageBox.Show("success");
    }
}

how can I provide this condition?

2

There are 2 best solutions below

10
styx On BEST ANSWER

maybe easier it will be to use KeysConverter

 private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            KeysConverter convertor = new KeysConverter();
            string keyPressed = convertor.ConvertToString(e.KeyValue);
            if (keyPressed == text1.Text)
            {
                //do stuff
            }
        }
2
Başar Kaya On

If you compare with one char text. You can try this.

private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (txt.Text.Length == 1 && e.KeyValue == (int)txt.Text[0]) //--------->> error
            {
                MessageBox.Show("success");
            }
        }