如何使用复选框关闭其他表单

时间:2018-09-08 17:38:01

标签: c# winforms

我有2种形式的MainUI和Log

我想使用复选框关闭MainUI的日志,但是我不知道该怎么做。

这是我在MainUI中的代码:

public void checkBox4_CheckedChanged(object sender, EventArgs e)
{            
        if (checkBox4.Checked == true)
        {
            Log F2 = new Log();
            F2.Show();
        }
        else if (checkBox4.Checked == false)
        {
            //Here should the exit code be for the Log form.
        }
}

日志:

public partial class Log : Form
{       
    public Log()
    {         
        InitializeComponent();
    }
    private void Log_Load(object sender, EventArgs e)
    {
    }
    public void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
    }

}

3 个答案:

答案 0 :(得分:3)

您需要为此使该变量在方法级别可见。为此,将其移至if块之外:

public class MainUIForm : Form
{
  private Log F2  = null;

  public void checkBox4_CheckedChanged(object sender, EventArgs e)
  {      

      if (checkBox4.Checked)
      {
        F2 = new Log();
        F2.Show();
      }
      else
      {
        F2?.Close(); // for closing which will dispose it
      }
   }
}

这假定您选中复选框时,需要为Log打开一个新的新窗口,并丢弃先前的窗口及其状态。

如果需要一次创建/实例化“日志”窗口,而只需要向用户显示并隐藏它,则取决于是否选中该复选框,那么您需要调整代码,例如:

public class MainUIForm : Form
{
  private Log F2 = new Log();

  public void checkBox4_CheckedChanged(object sender, EventArgs e)
  {      

      checkBox4.Checked ?
        F2.Show() :
        F2.Hide();

   }
}

答案 1 :(得分:1)

修改您的主表单应如此

///Make it as global
Log F2 = null;

public void checkBox4_CheckedChanged(object sender, EventArgs e)
    {      

        if (checkBox4.Checked == true)
        {   
            if(F2 == null)
                {
                  F2=new Log();
                }
            F2.Show();
        }
        else if (checkBox4.Checked == false && F2 != null)
        { 
            F2.Hide();
            F2.Close();
            //Here should the exit code be for the Log form.
        }
}

答案 2 :(得分:-1)

帖子解决了,我做了Log.Close();而不是Log.Hide()已修复!