A
A
Alexander2017-07-04 20:55:24
WPF
Alexander, 2017-07-04 20:55:24

How to compare entered character with character from text or Keyboard trainer in C#?

Tell me how this site works.
I want to write the same simulator in C #, but I can’t understand how it works.
Let's say there is text, we break it into an array of characters. And now what should I do with this array?
It can be compared with the pressed key, but how? Tried like this:

char[] znak;
public MainWindow()
{
    InitializeComponent();
    znak = textBlock1.Text.ToCharArray();
}
int rate = 0;
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{   
    if (e.Text == Convert.ToString(znak[rate])) 
    {
         textBox1.Text += e.Text;
         rate++;                
    }
    else
    {
         e.Handled = true;
    }
}

But for some reason, instead of "on", he gives out "anna" , with the cursor after the first letter.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vugar Panahov, 2017-07-14
@AlexNineteen

textBox1.Text += e.Text;
This line is superfluous here (you add the letter you pressed once again)
Also, do not forget about the space, it does not have "text", so you will also have to separately add a condition for it

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space && char.IsWhiteSpace(znak[rate]))
            {
                rate++;
            }
            else if (e.Key != Key.Space)
            {
                
            }
            else
            {
                e.Handled = true;
            }
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question