c# - 加载表单时禁用按钮并在关闭表单时启用按钮

标签 c# winforms

我想在加载第二个无模式表单 (Form2) 时禁用主表单上的按钮 (button3),然后在加载时重新启用该按钮无模式表单已关闭。

这是我尝试过的:

private void button3_Click(object sender, EventArgs e)
{
    Form2 p = new Form2(label1.Text);
    p.Show();

    if (p.Shown)
        this.button3.Click += new System.EventHandler(this.button3_Click);
    else
        this.button3.Click -= new System.EventHandler(this.button3_Click);
}

最佳答案

实现此目的的最佳方法是在显示 Form2 之前禁用 button3,并在 Form2 上使用 FormClosed 事件 表单关闭后重新启用 button3:

public partial class Form1 : Form
{
    ...

    private void button3_Click(object sender, EventArgs e)
    {
        // Instantiate the form and assign the FormClosed event
        var form = new Form2(label1.Text);
        form.FormClosed += Form2_FormClosed;

        // Disable button3
        button3.Enabled = false;

        // Show the form
        form.Show();
    }

    // Occurs when Form2 is closed
    private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        // Re-enable button3
        button3.Enabled = true;
    }
}

另一种方法,将 lambda 表达式分配给 FormClosed 事件:

private void button3_Click(object sender, EventArgs e)
{
    // Instantiate the form
    var form = new Form2(label1.Text);

    // Assign a lambda method to the FormClosed event to re-enable button3
    form.FormClosed += (s, a) => button3.Enabled = true;

    // Disable button3
    button3.Enabled = false;

    // Show the form
    form.Show();
}

关于c# - 加载表单时禁用按钮并在关闭表单时启用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502772/

相关文章:

c# - 创建类似 iSeries 的程序

c# - DEBUG - 不会为 SonarQube 之外的以下文件导入代码覆盖率

c# - 为 ASP.NET 编写月份和年份下拉列表的最佳方法是什么?

c# - 程序在 oWord.Documents.Open(oTemplatePath) 处卡住?

c# - 防止 Windows 窗体 datagridview 在单元格编辑后更改行

c# - Windows 手机 xml 解析

c# - Azure 中与 MongoDB 的离线数据同步

WebBrowser 中的 Javascript 控制台

winforms - Windows 窗体应用程序性能

.net - .NET 中 ClickOnce/智能客户端部署的陷阱/陷阱