Using a controller and events to decouple forms
The right way to do this is to separate the two forms from each other by introducing the Controller class and using events to change the state of the signal.
Here is an example.
First, create a new default Windows Forms application, WindowsFormsApplication1 and add two forms: form1 and form2 .
Then add to form1 button called "button1" and the label "label1".
Then add the checkbox1 flag to form2 .
In form1 designer form1 double-click the button to add a click handler for it.
In the form2 constructor, double-check the box to add a change handler for it.
Now add a new class called "Controller" and add the following code to it:
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { internal sealed class Controller { public void RunForm1() { _form1 = new Form1();
Now change Form1.cs to this:
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1: Form {
And change Form2.cs to this:
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form2: Form {
Finally, change Program.cs to this:
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Controller controller = new Controller(); controller.RunForm1(); } } }
Now run the program and click the button, and then check the box several times. You will see a shortcut in Form1.
Thus, you completely separate form1 from form2 and put the control logic in a separate controller class.