对于你们中的一些人来说,这可能很容易。
我有一个TextBox和一个ListBox。 ListBox为TextBox提供选项,并在DoubleClick事件上将所选项目的文本复制到TextBox。仅当TextBox触发Enter事件时,ListBox才可见。我不想讨论选择这种控制组合的原因。
当Form中的任何其他控件获得焦点时,我希望ListBox消失。因此,我捕获TextBox的Leave事件并调用ListBox.Visible = fale
问题是,当我单击ListBox以选择提供的选项时TextBox也将失去焦点,从而阻止我选择该选项。
我应该使用什么事件组合来保留ListBox以选择选项,但是当其他控件获得焦点时隐藏它?
答案 0 :(得分:1)
此示例将为您提供所需的结果:
public Form1()
{
InitializeComponent();
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
}
void textBox1_GotFocus(object sender, EventArgs e)
{
listBox1.Visible = true;
}
void textBox1_LostFocus(object sender, EventArgs e)
{
if(!listBox1.Focused)
listBox1.Visible = false;
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
textBox1.Text = listBox1.SelectedItem.ToString();
}
private void Form1_Shown(object sender, EventArgs e)
{
//if your textbox as focus when the form shows
//this is the place to switch focus to another control
listBox1.Visible = false;
}
答案 1 :(得分:1)
在Leave
方法中,您可以在更改ListBox
之前检查Visibility
是否是重点控制:
private void myTextBox_Leave(object sender, EventArgs e)
{
if (!myListBox.Focused)
{
myListBox.Visible = false;
}
}