Fill in the list of function ..?

first of all I am new to C #

I am trying to do something like this in a c # winforms application

when my application starts, the form will begin to collapse in the system tray. when I double click on it, it opens and sends a request to qpid broker to get some information. then the message is sent back and received in the listener in my application (I'm not sure if the code matters, but I will publish it anyway)

namespace MyApp
{
    public class MyListener : IMessageListener
    {
        public void MessageTransfer(IMessage m)
        {
            //do stuff with m
        }
    }
}

what I'm trying to do is fill in the list, which in this form is with the message received in this function, but I don’t know how to contact this specific form from the MessageTransfer function

+3
source share
2 answers

, , . , :

// event args class for transmitting the message in the event
public class MessageEventArgs : EventArgs
{
    public IMessage Message { get; private set; }

    public MessageEventArgs(IMessage message)
    {
        Message = message;
    }
}

:

public class MyListener : IMessageListener
{
    public event EventHandler<MessageEventArgs> MessageReceived;

    public void MessageTransfer(IMessage m)
    {
        OnMessageReceived(new MessageEventArgs(m));
    }

    protected void OnMessageReceived(MessageEventArgs e)
    {
        EventHandler<MessageEventArgs> temp = MessageReceived;
        if (temp != null)
        {
            temp(this, e);
        }
    }
}

, .


, . :

  • MessageReceived IMessageListener
  • IMessage Text.

:

public partial class MainUI : Form
{
    private IMessageListener _messageListener;

    public MainUI()
    {
        InitializeComponent();
        _messageListener = new MyListener();
        _messageListener.MessageReceived += MessageListener_MessageReceived;
    }

    void MessageListener_MessageReceived(object sender, MessageEventArgs e)
    {
        _messageListBox.Items.Add(e.Message.Text);
    }

}
+5

, , .

  • :

    public delegate void MessageHandler(IMessage m);
    public event MessageHandler MessageReceived;
    
  • MessageTransfer:

        if (MessageReceived != null)
            MessageReceived(m);
    
  • :

:

    _listener.MessageReceived += new MessageHandler(Form1_MessageReceived);

:

    void Form1_MessageReceived(IMessage m)
    {
        // add the message to the list
    }

, , , .

+1

Source: https://habr.com/ru/post/1745739/


All Articles