我之前曾询问过如何在C#中选择动态创建的列表框项目的问题.现在的问题是当弹出列表框时获得焦点!我无法继续输入,除非我选择一个项目或按Esc,我已明确定义将焦点设置回我的TextBox.
具有讽刺意味的是,我的KeyDown事件中有一个条件,即如果按下向上或向下箭头键,则设置焦点ListBox以便用户可以选择项目,但不要转移焦点以便用户可以继续自由键入.
就像我们在Visual Studio上所做的那样,当用户按下一个点时,他没有被阻止并被迫从Intellisense列表中选择一个项目,但是他可以继续输入并且或者在任何时候使用向上或向下箭头键来选择适当的项目.
我无法使用下面的代码实现相同的功能.我怎么能像上面提到的那样工作呢?
我需要说使用ActiveControl和transferFocus,使用this.Focus()之前lst.Focus(),禁用和启用文本框它们都不起作用!
private void txtResults_KeyDown(object sender, KeyEventArgs e)
{
string[] words= ((TextBox)sender).Text.Split(' ');
string s = sampleWord.Text = words[words.Length - 1];
if (e.KeyCode == Keys.OemPeriod)
{
ShowPopUpList(s);
lst.Focus(); //This transfers the focus to listbox but then prevents user
//from being able to type anymore unless he/she chooses an item!
}
else if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up)
{
lst.Focus();//doesnt work :-/
}
else
{
lst.Hide();
txtResults.Focus();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您希望用户能够继续在文本框中键入内容,同时仍然操作列表框的选择,那么您将不得不伪造它:当您显示列表框时,实际上不要将焦点设置到列表框。KeyDown相反,在文本框的事件中手动更改列表框的选择。像这样的东西:
private void txtResults_KeyDown(object sender, KeyEventArgs e)
{
string[] words = ((TextBox)sender).Text.Split(' ');
string s = sampleWord.Text = words[words.Length - 1];
if (e.KeyCode == Keys.OemPeriod)
{
ShowPopUpList(s);
lst.SelectedIndex = 0;
}
else if (lst.Visible && e.KeyCode == Keys.Up)
{
// manipulate the selection on the listbox (move up)
if (lst.SelectedIndex > 0)
lst.SelectedIndex -= 1;
// eat the keypress so it textbox doesn't get it and move the cursor
e.Handled = true;
}
else if (lst.Visible && e.KeyCode == Keys.Down)
{
// manipulate the selection on the listbox (move down)
if (lst.SelectedIndex < lst.Items.Count - 1)
lst.SelectedIndex += 1;
// eat the keypress so it textbox doesn't get it and move the cursor
e.Handled = true;
}
else if (lst.Visible && e.KeyCode == Keys.Enter)
{
// insert current list box selection into text box and hide the list
txtResults.Text += lst.SelectedItem;
txtResults.SelectionStart = txtResults.Text.Length;
lst.Hide();
// eat the keypress to prevent the textbox (and the form) from acting on it
e.SuppressKeyPress = true;
e.Handled = true;
}
else
{
lst.Hide();
}
}
Run Code Online (Sandbox Code Playgroud)