1

I have a Windows Form, with a ListView and a TextBox placed right on top of it. Also there is a button named 'Submit' on the Form with AcceptButton set to true.

Now, my requirement is that, whenever I load the form and hit Enter, Submit button gets triggered, which is fine. But, when I select the TextBox and type something in it and then hit Enter, the focus should come to the ListView , but not the AcceptButton

How can I achieve this?

pradeepradyumna
  • 952
  • 13
  • 34

1 Answers1

2

You can set the AcceptButton based on the active control, or as a better option, handle ProcessDialogKey yourself. This is the method which contains the logic for AcceptButton.

So you can override it, for example:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.Enter)
    {
        if (this.ActiveControl == this.textBox1)
        {
            MessageBox.Show("Enter on TextBox1 handled.");
            return true; //Prevent further processing
        }
    }
    return base.ProcessDialogKey(keyData);
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398