c# event handling between two forms

前端 未结 2 1120
执念已碎
执念已碎 2021-01-19 18:22

I have two forms and I am trying to capture an event generated from frmEventGenerate.cs in frmEventReceive.cs.

In this example I can receive the event from frmEven

相关标签:
2条回答
  • 2021-01-19 18:56
    //Receiver
    
    using System;
    using System.Windows.Forms;
    
    namespace eTest
    {
        public partial class frmMain : Form
        {
            public frmMain()
            {
                InitializeComponent();
            }
    
            public void ReceiveEvent(int i)
            {
                MessageBox.Show("Event Received from Form: " + i.ToString());
            }
    
            private void btnNew_Click(object sender, EventArgs e)
            {
                int num = 0;
                int x = 0;
    
                num = Convert.ToInt32(txtForms.Text);
    
                for (x = 0; x < num; x++)
                {
                    frmDL f = new frmDL();
                    f.Evt += ReceiveEvent;
                    f.iID = x;
                    f.Text = x.ToString(); 
                    f.Show();
                    f.Activate();
                    Application.DoEvents();
                }
            }
        }
    }
    
    //Sender
    
    using System;
    using System.Windows.Forms;
    
    namespace eTest
    {
        public delegate void myEventHandler(int i);
    
        public partial class frmDL : Form
        {
            public event myEventHandler Evt;
    
            public int iID = 0;
    
            public frmDL()
            {
                InitializeComponent();
            }
    
            public void SendEvent()
            {
                if (Evt != null)
                {
                    Evt(this.iID);
                }
            }
    
            private void btnEvent_Click(object sender, EventArgs e)
            {
                SendEvent();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-19 19:18

    In your constructor, after instantiating frmEventGenerate:

    frmGen.Evt += ReceiveEvent;
    

    You don't need new LinkEventHandler(...) any more - as of C# 2, there's a method group conversion available which you can use to convert from a method group (the name of a method) to a delegate type.

    EDIT: I hadn't seen that your event was static. That suggests you should actually use:

    frmEventGenerate.Evt += ReceiveEvent;
    

    ... and you don't need the frmGen variable at all.

    However, I would strongly discourage you from this - why do you want the event to be static in the first place? (I'd also urge you to name your types more sensibly - something like "EventGenerator" would be better here, for example. Ignoring the convention that type names should be in Pascal case leads to confusing code.)

    0 讨论(0)
提交回复
热议问题