Avalanchis
Avalanchis

Reputation: 4559

How can I override the default button on a form when focus is in a TextBox

I have a winform form which has typical OK and Cancel buttons.

The OK button is set as the default button. When the user presses the ENTER key, the form is closed.

The form also has a text box which has a Search button beside it. The text box allows the user to enter search text and the Search button initiates the search function.

I would like the user to be able to press the ENTER key when the text box has the input focus and have the search function activate.

The problem is that the form is grabbing the ENTER key event before the text box's handler gets it.

EDIT: I've tried using the following event handlers, but they never get hit, and the form closes when the Enter key is hit:

    private void txtFilter_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            Search();

            e.Handled = true;           
        }
    }

    private void txtFilter_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            Search();

            e.Handled = true;
        }
    }

I've also tried enabling the KeyPreview property on the form and implementing a KeyDown event handler for the form, but the Enter key never seems to cause any of these to be hit.

What is the best way to accomplish this?

Upvotes: 1

Views: 965

Answers (2)

LarsTech
LarsTech

Reputation: 81610

Try handling the Enter and Leave events of the TextBox to clear out your form's AcceptButton property:

private void txtFilter_Enter(object sender, EventArgs e) {
  this.AcceptButton = null;
}

private void txtFilter_Leave(object sender, EventArgs e) {
  this.AcceptButton = closeButton;
}

Then you can just process your KeyUp event as your want:

private void txtFilter_KeyUp(object sender, KeyEventArgs e)
{
  if (e.KeyCode == Keys.Enter)
  {
    Search();         
  }
}

Upvotes: 4

JimDel
JimDel

Reputation: 4359

Add a KeyDown event handler to the textBox and then add this to it

        if (e.KeyCode == Keys.Enter)
        {
            btnSearch.PerformClick();
        }

Upvotes: 0

Related Questions