简体   繁体   中英

How to know when a button is clicked in form1 but know in form2 C#

C#. Hello... I have 2 forms => Form1 with a button and Form2. I want to know how i can mannage the event of the button of the Form2 in Form1. So when i make a click in form2 i want to know in form1 to do something

Form1 can subscribe to the events of Form2. You need a handle onto Form2 in Form1 but then you can simply write:

instanceOfForm2.Button.Click += handlerInForm1;

Form1 requires a reference to Form2. Then, you just hook up an event handler in Form1 to the button in Form2.

// code in form1 might look something like

public void SubscribeToEvents()
{
   // get Form2 reference
   var form2 = GetForm2Reference();
   form2.Button.Click += ButtonOnForm2EventHandler;
}

public void ButtonOnForm2EventHandler(object sender, EventHandlerArgs e)
{
   // some code
}

As stated by others but without making public controls or finding references if you already have them:

In form2 create a method to send other method to subscribe the button click:

   public void SubscribeToButton(EventHandler eh) {
       button1.Click += eh;
   }

in form1 subscribe to form2:

   form2.SubscribeToButton(this.f2_button_Click);

and have a method in it that will execute on click

   private void f2_button_Click(object sender, EventArgs e) {
   }

I actually written the wrong order, so please threat form1 as form2 and viceversa.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM