单击按钮时隐藏和显示第二个表单

Hide and Show Second form on Button Click

我想通过单击按钮显示另一个表单 (Form2)。基本上当在 Form1 中单击按钮时,应该显示另一个表单(Form2),但这不应该隐藏 Form1,并且应该将 Form1 中的按钮文本更改为 "Hide Progress"。当再次单击此按钮时,Form2 应该隐藏并且按钮中的文本应该更改为 "Show Progress".

以下是我为完成这项工作所做的努力。当我单击显示进度按钮时,它会带来 Form2 并更改按钮中的文本。但是当我再次单击按钮而不是隐藏 Form2 时,它会打开 Form2 的另一个实例。

可能是因为 bool 值没有保存。

这是我的按钮事件处理程序代码。

public partial class Main : Form
    {
       public string output_green, output_grey, output_blue, output_black;
       public bool visible;
 private void button1_Click(object sender, EventArgs e)
        {

            output progressWindow = new output();

            if (visible == false)
            {
                progressWindow.Show();
                button1.Text = "Hide Progress";
                visible = true;
            }

            else
            {
                progressWindow.Show();
                button1.Text = "Show Progress";
                visible = false;

            }

        }
}

我怎样才能达到我需要的目的。

问题:

每次单击 button1 都会初始化一个 new progressWindow。

此外,您在其他部分使用 progressWindow.Show() 而不是 Hide()

解法:

button1_Click 中声明 progressWindow。然后从 button1_Click 初始化它。现在它只会被初始化一次(使用if)。

output progressWindow = null;
private void button1_Click(object sender, EventArgs e)
{            
        if(progressWindow == null)
            progressWindow = new output();
        if (button1.Text == "Show Progress")
        {
            progressWindow.Show();
            button1.Text = "Hide Progress";
        }
        else
        {
            progressWindow.Hide();
            button1.Text = "Show Progress";
        }
    }
}

对于进度 window 的生命周期与主要形式保持一致的较短解决方案:

    output progressWindow = new output();
    private void button1_Click(object sender, EventArgs e)
    {
        progressWindow.Visible = !progressWindow.Visible;
        button1.Text = (progressWindow.Visible) ? "Hide Progress" : "Show Progress";
    }

在这里你不需要额外的布尔值,因为进度表本身完全能够告诉你它是否可见。

  // Creates a single instance only it it is request.
  private Output ProgressWindow
    {
      get 
          {
              return progressWindow?? (progressWindow= new Output(){Visible = false};
          }
    }

   private Output progressWindow;

    private void button1_Click(object sender, EventArgs e)
    {            
         ProgressWindow.Visible = !ProgressWindow.Visible;
         button1.Text = (ProgressWindow.Visible) ? "Hide Progress" : "Show Progress";

        }
    }