🙂
I’m making a C# typing program
and I want the user to be unable to type anything when he types a wrong letter,
(I want the typing cursor to freeze at its position)
and when he presses backspace, only then he could resume his typing.
I have done this program in C++ by manipulating the ConsoleScreenCursorCoordinates,
I tried to do the same in C# via manipulating textBox.Location but it didn’t work.
In my program, there are 2 textBoxes, the sourceTextBox and the TypingTextBox
there is also a string variable called ‘text’ which will read from a textFile
via a StreamReader and then I use this text variable to compare each element from it with what the user is typing.
I tired this:
bool madeMistake = false;
Point CurrentTypingPosition;
string whatIsWrittenBeforeTheMistake = "";
private void TypingTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
if (!madeMistake)
{
if (e.KeyChar == text[typingIndex])
{
typingIndex++;
}
else if (e.KeyChar == backspace)
{
typingIndex--;
}
else
{
CurrentTypingPosition = TypingTextBox.Location;
madeMistake = true;
TypingTextBox.Text += " ";
TypingTextBox.Location = CurrentTypingPosition;
whatIsWrittenBeforeTheMistake = TypingTextBox.Text;
}
}
else
{
if (e.KeyChar == backspace)
madeMistake = false;
else
{
TypingTextBox.Text = whatIsWrittenBeforeTheMistake;
TypingTextBox.Location = CurrentTypingPosition;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Another variation on this is to use the
Handledproperty of theKeyPressevent args, so you get something like: