I am implementing a search function in a windows form in c#. I have set KeyPreview
to true on the form and have added an event handler for KeyDown
so I can catch things like ctrl+f
, esc
and enter
.
I am catching these keys just fine and I'm able to make my text box appear, but I am unable to type into the box. All of the keys are going to PortsTraceForm_KeyDown(...)
but they never make it to the text box. According to the msdn page about KeyPreview
, setting e.Handled to false should cause the event to pass to the view in focus (the text box), but this isn't happening. I have not registered a KeyDown
event for the text box, so it should be using the default behavior. Have I missed something?
KeyDown event:
private void PortsTraceForm_KeyDown(object sender, KeyEventArgs e)
{
e.SuppressKeyPress = true;
e.Handled = false;
if (e.KeyData == (Keys.F | Keys.Control)) // ctrl+f
{
e.Handled = true;
ShowSearchBar();
}
else if (e.KeyCode == Keys.Escape) // esc
{
e.Handled = true;
HideSearchBar();
}
else if (e.KeyCode == Keys.Enter) // enter
{
if (searchPanel.Visible)
{
e.Handled = true;
if (searchShouldClear)
SearchStart();
else
SearchNext();
}
}
}
show search bar:
private void ShowSearchBar()
{
FindBox.Visible = true;
FindBox.Focus(); // focus on text box
}
hide search bar:
private void HideSearchBar()
{
this.Focus(); // focus on form
FindBox.Visible = false;
}
Your TextBox likely does not have focus even though you are calling
Focus()
. From the documentation:You can check the return value of
Focus()
for success, but I have had little luck in the past using that method to set focus to an arbitrary control. Instead, try using the method that the documentation suggests, i.e., callSelect()
.EDIT:
Nevermind (though it's still valid advice), I think I see your problem:
Why are you doing this? Again, from the docs:
So you are intentionally preventing the TextBox from getting key events. If you want to pass the event through you shouldn't be setting that property to
false
.