仅当焦点在特定文本框上时,才能在Windows窗体上显示按钮吗?
使用这种方法进行了尝试:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
button3.Visible = false;
}
运气不好,因为按钮单击然后不起作用,因为在文本框失去焦点后立即隐藏了按钮,从而阻止了按钮3_Click(/*…*/){/*…*/}事件的触发.
现在,我这样做:
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("OK");
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void textBox2_Leave(object sender, EventArgs e)
{
//button3.Visible = false;
DoAfter(() => button3.Visible = false);
}
private async void DoAfter(Action action, int seconds = 1)
{
await Task.Delay(seconds*1000);
action();
}
窗体现在等待一秒钟,然后才隐藏button3.
有没有更好的办法?
解决方法:
我认为您只想在焦点位于特定文本框或焦点位于按钮上时显示按钮.
为此,您可以在textBox2的Leave事件中检查button3的Focused属性,并且仅在按钮没有焦点时才隐藏按钮.请注意,在textBox2的Leave事件触发之前,按钮将获得焦点.
然后,在button3失去焦点并且焦点移到textBox2之外的其他情况下,您将需要隐藏该按钮.您可以在此处使用完全相同的技术,方法是处理button3的Leave事件,如果textBox2没有焦点,则仅隐藏button3.
以下代码应符合您的要求:
private void textBox2_Leave(object sender, EventArgs e)
{
if (!button3.Focused)
{
button3.Visible = false;
}
}
private void button3_Leave(object sender, EventArgs e)
{
if (!textBox2.Focused)
{
button3.Visible = false;
}
}
private void textBox2_Enter(object sender, EventArgs e)
{
button3.Visible = true;
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked");
}