Search code examples
c#winformskeydownbuttonclickkeyeventargs

C# Compare the Key Pressed on the Keyboard


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?


Solution

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