简体   繁体   English

Windows窗体事件订阅c#

[英]Windows Forms Event Subscription c#

I have a sample form with 3 windows. 我有一个带有3个窗口的示例表单。 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. 在我的主窗体上,我将按一下按钮,让它在EventCode类中处理代码,然后调用事件。 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: 这是我在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: 在窗口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 对窗口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. 如果您创建EventCode的新实例并订阅事件,则仅当您在该特定实例上调用Process时,才会引发该事件。

Quick solution: pass the EventCode instance you create in the main window to the two child windows. 快速解决方案:将您在主窗口中创建的EventCode实例传递给两个子窗口。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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