Question

I have written a chat application which is working as desired apart from 1 line of code which is causing me problems.

In my MainForm I have:

        ChatBox cb = new ChatBox(person); 
        this.AddOwnedForm(cb);
        cb.Show();

This is displaying my chatbox, The problem is that this can only be used once If I try to append text in my chatbox thread:

        if (Ex.Message.Contains("chat ended"))
           {
             entryBox.Enabled = false;
             send.Enabled = false;
            if (displayBox.Enabled == true)
               {
                displayBox.AppendText("The User has left chat" + Environment.NewLine); // <- PROBLEM LINE OF CODE
                displayBox.Enabled = false; 
               }
           }

With the appendtext line uncommented that program will open a chat box once and close fine, but will freeze if I try to open another. Without this line of code the application works fine. I believe it may be a problem with the thread not ending correctly or something along those lines.

Any help on this issue would be greatly appreciated. If I have explained it poorly just ask and ill try and do a better job.

EDIT:

I tried using a delegate but I am still getting the same issue.

private void setDisplayBox(RichTextBox db)
    {
        if (this.InvokeRequired == false)
        {
            db.SelectionColor = Color.Red;
            db.AppendText("The User has left chat" + Environment.NewLine);
        }
        else
        {
        SetDisplayBox setDb = new SetDisplayBox(setDisplayBox);
        this.Invoke(setDb, new object[] { db });
        }
    }

This really has me stumped now :/.

Was it helpful?

Solution

I think you are trying to set the text in your user thread. Control.Enabled will work fine in another thread but you cannot set any value like Text over there. So append the text in your main thread. you can use displayBox.Invoke method to achieve this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top