-1

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?

ZiggZagg
  • 1,397
  • 11
  • 16
H.Marcus
  • 31
  • 7
  • There are several practical problems with this code. The distinction between the virtual key provided by KeyDown and the character provided by KeyPress is one. But most severely, how would you ever type any text inside the textbox if you also have the form objecting against it? The true intention is too hard to divine from the snippet. – Hans Passant Apr 15 '18 at 09:50

2 Answers2

0

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");
            }
        }
Başar Kaya
  • 354
  • 6
  • 13
0

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
            }
        }
styx
  • 1,852
  • 1
  • 11
  • 22