简体   繁体   中英

How to handle button click event from form1 in form2

I have two forms:

Form1.cs

namespace WindowsFormsApplication1    
    {
        public partial class Form : System.Windows.Forms.Form
        {
            Form2 form2;

            public Form()
            {
                InitializeComponent();
                form2 = new Form2(this);
            }
        }        
        public void buttonCalculate2axis_Click(object sender, EventArgs e)
        {
            // some code - it isn't important
        }
}

Form2.cs

Namespace WindowsFormsApplication1
{
public partial class Form2 : System.Windows.Forms.Form
{
    Form form1;
    public Form2(Form data)
    {
        InitializeComponent();
        form1 = data;
    }        
    private void Form2_VisibleChanged(object sender, PaintEventArgs e)
    {
    // some code - it isn't important
    }
}

I'm trying use the event public void buttonCalculate2axis_Click(object sender, EventArgs e) from Form1 in Form2 . So if i push the button in Form1 , in Form2 i will waiting for this event and after that i can go next in code. And if its possible i woun't use the private void Form2_VisibleChanged(object sender, PaintEventArgs e) only the click event.

If the form with the button has a reference to the form with the handler, and that handler is public , then you can just dynamically bind an event handler in code :

someButton.Click += new System.EventHandler(otherForm.SomeClickHandler);

In your code it looks like the click handler is in Form1 , and since you claim that the button is also in Form1 , so it's not clear what exactly you need to do here. But if you have a public handler in Form2 then you can use form2.YourHandlerFunction as the event handler.

Or if Form2 instead has the button and you want to use the handler in Form1 then Form2 would use the above code with form1. buttonCalculate2axis_Click form1. buttonCalculate2axis_Click as the event handler.

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