如何使用复选框 show/hide 表单?

How can I show/hide form with checkbox?

抱歉,我是 C# 的新手,不确定我做错了什么。

这是我使用的代码:

private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
{
    frmSmallMenu sm = null;
    if (chkSmallMenu.Checked) 
    { 
        if (sm is null || sm.IsDisposed)
        { 
            sm = new frmSmallMenu(); 
        } 
        sm.Show(); 
    } 
    else 
    {
        MessageBox.Show("close");
        sm?.Close(); 
    }
}

window 将打开,但当我取消选中该框时没有任何反应,我不知道为什么。 我曾尝试寻找答案,但没有任何效果。

试试这个:

frmSmallMenu sm = new frmSmallMenu();

    private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
    {
        if (chkSmallMenu.Checked == true)
        {
            sm.Show();
        }
        else
        {
            MessageBox.Show("close");
            sm.Hide();
        }
    }

通过首先查看另一个 Form 是否已经 运行 ,您的代码的这种修改可能会完成您想要的:

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// The following `uselessField ` is a `field`. See also 
        /// `(Since it is `unused`, you would get a CS0169 Warning in the "Error List" window)
        private int uselessField;

        /// <summary>
        /// **Event handler** of the "chkSmallMenu" `CheckBox` control on your `Form`.
        /// (You would probably get an IDE1006 Info in your "Error List" window because
        /// the control name and/or the event handler name respectively, starts with a lower case
        /// https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/naming-rules)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
        {
            // the following `sm` is a `variable`. See also 

            var sm = Application.OpenForms.OfType<frmSmallMenu>().FirstOrDefault();
            // the following `Checked` **property** belongs to the WinForms Checkbox class and `IsDisposed` belongs to the other `Form`
            if (chkSmallMenu.Checked)
            {
                if (sm?.IsDisposed != true)
                {
                    sm = new frmSmallMenu();
                }
                sm.Show();
            }
            else
            {
                MessageBox.Show("close");
                sm?.Close();
            }
        }
    }
}

这解决了我的问题:

frmSmallMenu sm = new frmSmallMenu();

private void chkSmallMenu_CheckedChanged(object sender, EventArgs e)
{
    if (chkSmallMenu.Checked == true)
    {
        sm.Show();
    }
    else
    {
        MessageBox.Show("close");
        sm.Hide();
    }
}