gpt4 book ai didi

c# - 如何使用事件和委托(delegate)在表单之间发送数据?

转载 作者:太空狗 更新时间:2023-10-29 22:52:46 26 4
gpt4 key购买 nike

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

不幸的是,那天我生病了,那天我不能去听课。

我再解释一下:

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

如下图所示:

enter image description here

当我发送消息时,它会显示在 ALL INSTANCES 的“已接收”文本框中。

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

怎么做?谢谢!!

最佳答案

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

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

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

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 类,用于处理在 Form 之间发送的“中央”消息列表。 Messages 类是单例(意味着它只能实例化一次),它允许一个列表在 Form 的所有实例中持久存在。所有表单将共享同一个列表,并在列表更新时收到通知。如您所见,“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 列表类型,它已经提供了一个您可以订阅的事件。

希望这对您有所帮助。

关于c# - 如何使用事件和委托(delegate)在表单之间发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718728/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com