5

我需要创建一个能够发送数据并从另一个Form实例接收数据的 Windows 窗体应用程序。什么意思,它们Form都是发布者和订阅者。

不幸的是,那天我病了,那天我不能参加讲座。

我再解释一下:

我有一个小聊天Form,他们有:新的实例按钮、收到的消息和发送消息。

正如您在下面看到的:

在此处输入图像描述

当我发送消息时,它将显示在所有实例的“已收到”文本框中。

我想我需要使用委托和事件。

怎么做?谢谢!!

4

1 回答 1

9

这是一个快速的解决方案。如果您有任何问题或发现评论令人困惑,请告诉我。

这是 Form 类(后面的代码)。请注意,一旦表单被实例化,它就会通过将事件处理程序“连接”到 Message 类中的 HandleMessage 事件来“订阅”事件。在 Form 类中,这是填充 ListView 的项目集合的地方。

每当单击 New Form 按钮时,都会创建并显示相同的 Form get(这允许代码重用,因为相同的逻辑对于 Form 的所有实例都是完全相同的)

public partial class Form1 : Form
{
    Messages _messages = Messages.Instance; // Singleton reference to the Messages class. This contains the shared event
                                            // and messages list.

    /// <summary>
    /// Initializes a new instance of the <see cref="Form1"/> class.
    /// </summary>
public Form1()
{
    InitializeComponent();

    // Subscribe to the message event. This will allow the form to be notified whenever there's a new message.
    //
    _messages.HandleMessage += new EventHandler(OnHandleMessage);

    // If there any existing messages that other forms have sent, populate list with them.
    //
    foreach (var messages in _messages.CurrentMessages)
    {
        listView1.Items.Add(messages);
    }
}

/// <summary>
/// Handles the Click event of the buttonNewForm control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void buttonNewForm_Click(object sender, EventArgs e)
{
    // Create a new form to display..
    //
    var newForm = new Form1();
    newForm.Show();
}

/// <summary>
/// Handles the Click event of the buttonSend control. Adds a new message to the "central" message list.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void buttonSend_Click(object sender, EventArgs e)
{
    string message = String.Format("{0} -- {1}", DateTime.UtcNow.ToLongTimeString(), textBox1.Text);
    textBox1.Clear();
    _messages.AddMessage(message);
}

/// <summary>
/// Called when [handle message].
/// This is called whenever a new message has been added to the "central" list.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="args">The <see cref="System.EventArgs"/> instance containing the event data.</param>
public void OnHandleMessage(object sender, EventArgs args)
{
    var messageEvent = args as MessageEventArgs;
    if (messageEvent != null)
    {
        string message = messageEvent.Message;
        listView1.Items.Add(message);
    }
}

}

这是我创建的一个 Messages 类,用于处理在表单之间发送的“中央”消息列表。Messages 类是一个单例(意味着它只能被实例化一次),它允许一个列表在表单的所有实例中保持不变。所有表单将共享同一个列表,并在列表更新时收到通知。如您所见,“HandleMessage”事件是每个表单在创建/显示时将订阅的事件。

如果您看一下 NotifyNewMessage 函数,Messages 类会调用它来通知订阅者发生了变化。由于 EventArgs 用于将数据传递给订阅者,因此我创建了一个特殊的 EventArgs 来将新添加的消息传递给所有订阅者。

class Messages
{
    private List<string> _messages = new List<string>();
    private static readonly Messages _instance = new Messages();
    public event EventHandler HandleMessage;

    /// <summary>
    /// Prevents a default instance of the <see cref="Messages"/> class from being created.
    /// </summary>
    private Messages() 
    {
    }

    /// <summary>
    /// Gets the instance of the class.
    /// </summary>
    public static Messages Instance 
    { 
        get 
        { 
            return _instance; 
        } 
    }

    /// <summary>
    /// Gets the current messages list.
    /// </summary>
    public List<string> CurrentMessages 
    {
        get
        {
            return _messages;
        }
    }

    /// <summary>
    /// Notifies any of the subscribers that a new message has been received.
    /// </summary>
    /// <param name="message">The message.</param>
    public void NotifyNewMessage(string message)
    {
        EventHandler handler = HandleMessage;
        if (handler != null)
        {
            // This will call the any form that is currently "wired" to the event, notifying them
            // of the new message.
            handler(this, new MessageEventArgs(message));
        }
    }

    /// <summary>
    /// Adds a new messages to the "central" list
    /// </summary>
    /// <param name="message">The message.</param>
    public void AddMessage(string message)
    {
        _messages.Add(message);
        NotifyNewMessage(message);
    }
}

/// <summary>
/// Special Event Args used to pass the message data to the subscribers.
/// </summary>
class MessageEventArgs : EventArgs
{
    private string _message = string.Empty;
    public MessageEventArgs(string message)
    {
        _message = message;
    }

    public String Message
    {
        get
        {
            return _message;
        }
    }
}

另外..为了正确“显示”消息,不要忘记将ListView控件的“View”属性设置为“List”。一种更简单(也是首选的方式)就是使用 ObservableCollection 列表类型,它已经提供了一个可以订阅的事件。

希望这可以帮助。

于 2012-12-05T10:09:19.747 回答