Search code examples
c#windowsenter

How to avoid selecting textbox value when press Enter?


Control nextControl;
if (e.KeyCode == Keys.Enter)
{     
    nextControl = GetNextControl(ActiveControl, !e.Shift);
    if (nextControl == null)
    {
        nextControl = GetNextControl(null, true);
    }
    nextControl.Focus();               
    e.SuppressKeyPress = true;
 }

I have this code to act ENTER Key as TAB but when I press Enter key it is selecting textbox value as in image

enter image description here


Solution

  • You can tell the TextBox to select nothing

    Control nextControl;
    
    if (e.KeyCode == Keys.Enter)
    {     
        nextControl = GetNextControl(ActiveControl, !e.Shift);
        if (nextControl == null)
        {
            nextControl = GetNextControl(null, true);
        }
        nextControl.Focus();
    
        TextBox box = nextControl as TextBox;
        if (box != null)
            box.Select(box.Text.Length, 0);
    
        e.SuppressKeyPress = true;
    }