Search code examples
c#winformstextboxcursorkeydown

TextBox Set Cursor at end after KeyUp or KeyDown


I have a list with previous entries of my TextBox. By using KeyUp / KeyDown I can scroll through this list showing the text in the TextBox.

Setting another string in the TextBox the edit-cursor should be at the end of the string in the Teemphasized textxtBox. myTextBox.Select(RTextBox.Text.Length, 0); is very useful here but after KeyUp this is setting the cursor not at the end of the text, it's one character before. After KeyDown its at the end, correct. I guess according to the naming preview the current character is not yet calculated in, but even adding +1 to the length doesn't work.

 private void MyTextBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        switch (e.KeyValue)
        {
            case (char)Keys.Up:
                myTextBox.Text = GetNewText();
                myTextBox.Select(myTextBox.Text.Length, 0);
                break;

            case (char)Keys.Down:                  
                myTextBox.Text = GetNewText();
                myTextBox.Select(myTextBox.Text.Length, 0);
                break;
        }
    }

 private void MyTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            switch (e.KeyChar)
            {
                case (char)Keys.Up:
                   // I'd guess setting the cursor here would be perfect
                   // but KeyUp/KeyDown can't be caught here, unfortunately
                   myTextBox.Select(RTextBox.Text.Length, 0);
                   break;
            }
         }

So I think that I have to set the cursore after the PreviewKeyDown-Event but in case of KeyUp / KeyDown I don't know if this is possible at all.

Any other event where I should set the cursor?

Edit: I'm using WinForms.


Solution

  • Try to add this line if it's a Keys.Up or a Keys.Down and use the KeyDown event:

    e.Handled = true;
    

    It means, that the normal behavior is skipped. At the end you have this:

    private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyValue)
        {
            case (char)Keys.Up:
                e.Handled = true;
                myTextBox.Text = GetNewText();
                myTextBox.Select(myTextBox.Text.Length, 0);
                break;
    
            case (char)Keys.Down:                  
                e.Handled = true;
                myTextBox.Text = GetNewText();
                myTextBox.Select(myTextBox.Text.Length, 0);
                break;
        }
    }