c# - 仅当焦点在文本框上时显示按钮

标签 c# winforms

只有当焦点位于特定文本框时,才可以在 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

有没有更好的方法?

最佳答案

我认为您只想在焦点位于特定文本框上时才显示按钮或者焦点位于按钮上

为此,您可以在 textBox2Leave 事件中检查 button3Focused 属性,并且仅如果按钮没有焦点,则隐藏按钮。请注意,在 textBox2Leave 事件触发之前,按钮将获得焦点。

然后,您需要在 button3 失去焦点并且焦点移动到 textBox2 以外的地方的情况下隐藏按钮。您可以在此处使用完全相同的技术,方法是处理 button3Leave 事件,并且仅在 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/

相关文章:

c# - 可检查的表头复选框不起作用

c# - 在c#中编码和解码安全吗?

c# - 下拉大小设置未采用

.net - 是否可以在 Winforms TreeView 中使节点不可见?

c# - 从资源中添加字体文件

c# - 从 C# 在 Oracle 数据库中输入日期参数​​的正确格式是什么

c# - 如何在低版本(.Net)上使用Excel Interop?

c# - 使用 MySqlCommand.ExecuteNonQuery 将几何数据插入表中

C# MySql 查询结果到组合框

c# - 将带有动画元素的 C# winforms Panel 或 PictureBox 保存到 gif 文件?