Search code examples
c#wpftextbox

Clearing a TextBox leaves an invisible character


I'm developing a textbased RPG . If you type something into the textbox (tUser), the method Input() gets called and processes your query. If it matches a certain condition, something else, e. g. exiting the game, will happen.

public void Input()
{
    if (tUser.Text.ToLower() == "ende" || listening)
    {
        if (tUser.Text.ToLower() == "ende")
        {
            if (MessageBox.Show(playername + 
                ", wollt Ihr wirklich das Spiel ohne Speichern verlassen?", "Beenden", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Application.Exit();
            }
        }
        else
        {
            input = tUser.Text;

            if (accept == 1 && !input.Any(char.IsDigit))
            {
                tRPG.AppendText("\nBitte gebt nur eine Zahl ein!");
            }
            else
            {     
                listening = false;
            }
        }        
    }

    // Reset
    input = "";
    tUser.Clear();
}

Your query will be submitted if you press Enter. After the process is done, the TextBox is being cleared.
If you try the same or any other command (again), nothing's going to happen, until you delete an "invisible" character in the TextBox.
I have also tried tUser.ClearUndo().

What is this character and how can I avoid it?


Solution

  • For some reason, the textbox keeps a carriage return. Adding e.Handled = true to the method which calls Input() solves this issue.

    private void tUser_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Enter)
        {
            e.Handled = true;
            Input();
        }
    }
    

    e.Handled prevents the enter message from being processed after this handler has finished (source).