只有当焦点位于特定文本框时,才可以在 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;
}
运气不好,因为按钮点击不起作用,因为按钮在文本框失去焦点后立即被隐藏,阻止它触发 button3_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();
}
Form 现在等待一秒钟,然后才隐藏 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");
}
关于c# - 仅当焦点在文本框上时显示按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25637685/