2

我正在运行服务器/客户端通信。现在我想在服务器上写一些东西textBox并在客户端上显示,textBox所以我从服务器向客户端发送一条消息,客户端使用静态方法接收它:

    static void Client_MessageReceived(object sender, MessageEventArgs e)
    {
        //Client only accepts text messages
        var message = e.Message as ScsTextMessage;
        if (message == null)
        {
            return;
        }
    }

现在我只想textBox通过这个静态方法将消息附加到客户端。我想我需要某种东西,但我不知道该怎么做,而且我在Googleinvoke上找不到任何有用的东西。

4

2 回答 2

1

调用方法

public void AppendText(string what, bool debug = false)
     {
         if (debug)
             return;
         if (this.InvokeRequired)
         {
             this.Invoke(
                 new MethodInvoker(
                 delegate() { AppendText(what); }));
         }
         else
         {
             DateTime timestamp = DateTime.Now;
             tbox.AppendText(timestamp.ToLongTimeString() + "\t" + what + Environment.NewLine);
         }
     }

消息接收方法

 private void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            //Client only accepts text messages
            var message = e.Message as ScsTextMessage;
            if (message == null)
            {
                return;
            }
            AppendText(message.Text, false);

            //Console.WriteLine("Server sent a message: " + message.Text);
        }
于 2013-01-18T23:10:37.187 回答
0
// Program.cs

public static ProgramForm Form;

publi static void Main()
{
    // ...
    Application.Run(Form = new ProgramForm());
    // ...
}

public static void ChangeText(String message)
{
    Form.TextBox1.Text = message;
}

// ProgramForm.cs

private void Client_MessageReceived(object sender, MessageEventArgs e)
{
    if (e.Message != null)
        Program.ChangeText(e.Message);
}
于 2013-01-18T23:41:52.747 回答