Lo siento, soy nuevo en C# y no estoy seguro de lo que estoy haciendo mal.
Aquí está el código que estoy usando:
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(); } }La ventana se abrirá, pero cuando desmarco la casilla, no sucede nada y no tengo idea de por qué. He intentado buscar una respuesta pero nada me ha funcionado.
Prueba esto:
frmSmallMenu sm = new frmSmallMenu(); private void chkSmallMenu_CheckedChanged(object sender, EventArgs e) { if (chkSmallMenu.Checked == true) { sm.Show(); } else { MessageBox.Show("close"); sm.Hide(); } }Esta modificación de su código probablemente haría lo que desea al ver primero si el otro Form ya se está ejecutando o no:
namespace WinFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// The following `uselessField ` is a `field`. See also https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property /// `(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 https://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a-property 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(); } } } }Esto solucionó mi problema:
frmSmallMenu sm = new frmSmallMenu(); private void chkSmallMenu_CheckedChanged(object sender, EventArgs e) { if (chkSmallMenu.Checked == true) { sm.Show(); } else { MessageBox.Show("close"); sm.Hide(); } }