【问题标题】:C# - Add Item to Listbox on Form from a ClassC# - 从类中将项目添加到表单上的列表框
【发布时间】:2016-04-24 05:13:26
【问题描述】:

我正在尝试用 C# 做一个简单的 WebSocket 服务器,它将与 JavaScript 中的客户端通信,我正在测试的代码是这样的:

Websocket-sharp 服务器

using System;
using System.Windows.Forms;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace MyProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var wssv = new WebSocketServer(8081);

            wssv.WaitTime = TimeSpan.FromSeconds(3);

            wssv.AddWebSocketService<NFP>("/");

            wssv.Start();
        }
    }

    public class NFP : WebSocketBehavior
    {
        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine(e.Data);

            Send("Received");
        }

        protected override void OnError(ErrorEventArgs e)
        {
            //Console.WriteLine(e.Exception);
        }

        protected override void OnClose(CloseEventArgs e)
        {
            //Console.WriteLine(e.Code);
        }
    }
}

现在我想知道,对于 Form1 上已经打开的 ListBox,如何发送在 OnMessage 收到的消息?

【问题讨论】:

    标签: c# class websocket listbox server


    【解决方案1】:

    更好的解决方案是在c#中使用Binding。

    但是如果你想要一个快速的解决方案,你可以创建这个类:

    public static class ListBoxAdder
    {
        public static void Add(ListBox listbox, string newItem)
        {
            listbox.Items.Add(newItem);
        }
    }
    

    在Form1中声明

    public static ListBox listBox;
    

    最后

    protected override void OnMessage(MessageEventArgs e)
    {
      ListBoxAdder.Add(Form1.listBox, e.Data);
    }
    

    【讨论】:

      【解决方案2】:
      1. 将目标列表框定义为 NPF 类的属性:

        public ListBox Target {get; set;}

      2. 在 button1_Click 方法中设置目标:

        wssv.Target = myListBox;

      3. 当您收到消息时,将其添加到列表框中。但是,由于您与 UI 线程处于不同的线程中(这是唯一可以修改表单上的控件的线程),因此您必须调用 Target 上的 Invoke 成员来完成您的工作:

        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine(e.Data);
        
            if (Target != null)
                Target.Invoke( () => {Target.Items.Add(e.Message);});
        
            Send("Received");
        }
        

      【讨论】:

      • 目标不起作用,因为“wssv”是一个新的 WebSocketServer 而不是 NFP 类的实例。
      • @Anderson Costa - 好吧,我弄错了那部分 - 我不熟悉 WebSocketeServer 类,但你必须能够以某种方式深入到 NFP 对象(可能来自 @ 的返回值987654326@ ? ) 然后在那里设置 Target 属性。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      相关资源
      最近更新 更多