How to automatically lower case the 2nd letter of a word in a WPF textbox?(C#)

I am trying to create a function which automatically lower cases the 2nd Letter of a Word
in a textbox. I already tried it with this function but i ran into one problem:

After the function detects a 2nd letter of a word which isn’t written in lower case it sets the letter to capital. But after that the writing cursor moves to the beginning of the textbox. (the cursor moves in front of the already written words)

private void Text1_KeyDown(object sender, KeyEventArgs e)
            string erg;
            string input;
            input = Convert.ToString(Text1.Text);
            if (input.Length > 1)
                erg = input[0] + input.Substring(1, 1).ToLower() + input[2..];
                Text1.Text = erg;

Thank You in advance!

>Solution :

You need to remember and then set the CaretIndex to the correct position, like so

var originalIndex = Text1.CaretIndex;

// Your code

Text1.CaretIndex = originalIndex;

Leave a Reply