【问题标题】:Why wont my method append this richTextBox为什么我的方法不附加这个richTextBox
【发布时间】:2018-04-22 23:07:25
【问题描述】:

我目前正在尝试制作即时消息应用程序。

有一个客户端和一个服务器。服务器运行良好,但由于某种原因,当我调用某个函数来更新 UI 时,TextBox 没有添加文本。

以下是我的代码示例 - 在我的应用程序中从不同的表单调用更新 UI:

public ChatWindow()
    {
        InitializeComponent();
        Thread timerThread = new Thread(Main.ReceiveLoop);
        timerThread.Start();
    }

    private void txtChatLog_TextChanged(object sender, EventArgs e)
    {

    }

    private void btnSendMessage_Click(object sender, EventArgs e)
    {
        string clientReply = txtReply.Text;
        string Message = "ClientMsg§" + clientReply;
        var time = DateTime.Now;
        txtChatLog.AppendText($"{time} client: {clientReply}");
        txtChatLog.AppendText(Environment.NewLine);
        Main main = new Main();
        main.ChatResponse(Message);
        txtReply.Text = "";

    }

    public void UpdateChatLog(string message)
    {
        var time = DateTime.Now;
        string newMessage = message.Split('$')[1];
        string messageToDisplay = $"{time} Server: {newMessage}";
        MessageBox.Show(messageToDisplay);
        txtChatLog.AppendText(messageToDisplay);
        txtChatLog.AppendText(Environment.NewLine);
    }

    private void ChatWindow_Load(object sender, EventArgs e)
    {

    }

当我使用 messagebox.show() 进行检查时,客户端正在挑衅地接收来自服务器的消息;

当按下发送消息按钮时,富文本框也会更新。但由于某种原因,它不会通过 UpdateChatLog 方法进行更新。

任何帮助将不胜感激。

谢谢你提前!

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    从您粘贴的代码中,您不会调用 UpdateChatLog 方法。 尝试添加 UpdateChatLog(message);到 btnSendMessage_Click 方法。

    【讨论】:

    • UpdateChatLog 的形式不同,它不需要在发送消息按钮中。它被挑衅地调用,因为如前所述,messagebox.Show 被调用并显示。只是文本框没有改变。
    • @JeremyGriffin 尝试调试并检查变量消息是否有变化,然后检查这一行:string newMessage = message.Split('$')[1];可能是 newMessage 无法获得价值。
    • Messagebox.show 显示该变量在文本框更改之前被调用,因此它是 deffo 获取值。
    【解决方案2】:

    尝试刷新文本框:txtChatLog.Refresh()

    【讨论】:

    • 试了一下,收效甚微。
    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多