简体   繁体   中英

Windows Forms Event Subscription c#

I have a sample form with 3 windows. Each window has a label and the main form has a button.

I have a class with the following code:

    public class CustomEventArgs : EventArgs
{
    public string Message { get; set; }
    public CustomEventArgs(string message)
    {
        Message = message;
    }
}

public delegate void CustomEventHandler(object sender, CustomEventArgs args);

public class EventCode
{
    public void Process()
    {
        var cea = new CustomEventArgs("I was processed");
        if (MyEvent != null)
        {
            MyEvent.Invoke(this, cea);
        }
    }

    public event CustomEventHandler MyEvent;
}

On my main form, I am going to push the button and have it process code in my EventCode class, and then invoke the event. I want the event to send a message to both forms that are open, which will then display a message on the screen.

Here is my button click code in Form1:

        private void Form1_Load(object sender, EventArgs e)
    {
        Window1 w1 = new Window1();
        w1.Show();

        Window2 w2 = new Window2();
        w2.Show();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        EventCode ec = new EventCode();
        ec.Process();
    }

In Window 1:

EventCode ec = new EventCode();
    public Window1()
    {
        InitializeComponent();
        ec.MyEvent += new CustomEventHandler(ec_MyEvent);
    }

    void ec_MyEvent(object sender, CustomEventArgs args)
    {
        label1.Text = args.Message;
    }

Repeated for Window 2

When I click on the button, the event subscription does not display the text on each of the forms. If i create an event subscription on the main form, it will display.

I am not sure which route to take to make this functionality to work.

Thoughts?

Subscriptions to events only work for the instances you subscribe on. If you create a new instance of EventCode and subscribe to the events, the event will only be raised if you call Process on that specific instance.

Quick solution: pass the EventCode instance you create in the main window to the two child windows.

public Window1(EventCode eventCode)
{
    InitializeComponent();
    eventCode.MyEvent += new CustomEventHandler(ec_MyEvent);
}

void ec_MyEvent(object sender, CustomEventArgs args)
{
    label1.Text = args.Message;
}

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