Search code examples
c#winformsnamespacescode-reuse

Reuse code from class to class


I have 2 winforms called AppNamespace.MYForm and AnotherNamespace.AnotherForm.
They both have a button.

When the user click on the button of AnotherNamespace.AnotherForm I would like to perform a click on the button located on AppNamespace.MYForm.

However, there is a constriant that AnotherNamespace cannot use AppNamespace.
This prevents me from doing :

AppNamespace.MYForm firstForm = new AppNamespace.MYForm();
firstForm.button.PerformClick();

Any ideas?


Solution

  • Manually executing event of any control is a bad practice. Create separate method and execute it instead.

    You can create interface then implement it to both forms. The interface should contains a method PerformClick.

    public Interface IMyInterface
    {
        void PerformClick(string _module);
    }
    
    public class Form1 : IMyInterface
    {
       public void IMyInterface.PerformClick(string _module) 
       {
          //CODE HERE
          if (Application.OpenForms["Form2"] != null && _module != "Form2")
              ((IMyInterface)Application.OpenForms["Form2"]).PerformClick(_module);
       }
    
       private void button1_Click(object sender, EventArgs e)
       {
           this.PerformClick(this.Name);
       }
    }
    
    
    public class Form2 : IMyInterface
    {
       public void IMyInterface.PerformClick() 
       {
          //CODE HERE
          if (Application.OpenForms["Form1"] != null && _module != "Form1")
              ((IMyInterface)Application.OpenForms["Form1"]).PerformClick(_module);
       }
    
       private void button1_Click(object sender, EventArgs e)
       {
           this.PerformClick(this.Name);
       }
    }