我在c#中的窗体窗体中实现了一个搜索功能。我在表单上设置了KeyPreview
为true,并为KeyDown
添加了一个事件处理程序,因此我可以捕获诸如ctrl+f
,esc
和enter
之类的事件。当在窗体上使用TextPreview时,TextBox没有收到键值
我抓住这些键就好,我可以让我的文本框出现,但我无法输入到框中。所有的钥匙都会去PortsTraceForm_KeyDown(...)
,但他们从来没有把它放到文本框中。根据关于KeyPreview
的msdn页面,将e.Handled设置为false应该会导致事件传递给焦点视图(文本框),但这不会发生。我没有为文本框注册KeyDown
事件,所以它应该使用默认行为。我错过了什么吗?
KeyDown事件:
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();
}
}
}
显示搜索栏:
private void ShowSearchBar()
{
FindBox.Visible = true;
FindBox.Focus(); // focus on text box
}
隐藏搜索栏:
private void HideSearchBar()
{
this.Focus(); // focus on form
FindBox.Visible = false;
}
首先我会在TextBox的Lost ficus事件上订阅,然后检查FindBox.Focus();以某种方式调用TextBox的方式失去焦点.. – Tigran
这是一个很好的建议,除了光标仍然可见和闪烁,所以我相当积极,它不失去焦点。 – mtmurdock