I am learning about networking in C# and to do so i am making a simple instant message server/client app. everything is going fine. i am currently testing it by inputting my own ip address as the target to send/receive on same machine.

but, i can only send one message then nothing. when i finally give up and exit the app(running it from vstudio) it gives this error:

System.InvalidOperationException was unhandled
  Message=Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.WaitForWaitHandle(WaitHandle waitHandle)
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
       at IMTest.IMForm.AddListBoxItem(Object item) in C:\Users\rootchord\Documents\Visual Studio 2010\Projects\IMTest\IMTest\Form1.cs:line 97
       at IMTest.IMForm.ReceiveMessages() in C:\Users\rootchord\Documents\Visual Studio 2010\Projects\IMTest\IMTest\Form1.cs:line 62
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
public partial class IMForm : Form
    {
        TcpListener myList;
        public string theirip = "";
        IPAddress myip;
        private Thread receive;
        Socket s;

        public IMForm()
        {
            InitializeComponent();
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress anip in localIPs) 
            {
                if (!anip.ToString().Contains(":"))
                {
                    myip = anip;
                }
            }
            MessageBox.Show(myip.ToString());
            TargetForm settarget = new TargetForm();
            settarget.ShowDialog();
            theirip = settarget.TargetIPBox.Text;
        }

        private void Form1_Load(object sender, EventArgs e)
        {            
            receive = new Thread(new ThreadStart(ReceiveMessages));
            receive.Start();
            this.AcceptButton = SendButton;
        }
 

       private void ReceiveMessages()
       {
           myList = new TcpListener(myip, 8001);
           myList.Start();
           s = myList.AcceptSocket();
           do{
               byte[] b = new byte[100];
               int k = s.Receive(b);
               string message = "";
               for (int i = 0; i < k; i++)
               {
                   message += Convert.ToChar(b[i]);
               }
               AddListBoxItem(message);
           }while(true);
       }


       private void SendMessages(string message)
       {
           TcpClient tcpclnt = new TcpClient();
           try
           {
               tcpclnt.Connect(theirip, 8001);
           }catch(Exception e)
           {
               MessageBox.Show("Error: " + e);
           }

           Stream stm = tcpclnt.GetStream();
           ASCIIEncoding asen = new ASCIIEncoding();
           byte[] ba = asen.GetBytes(message);
           stm.Write(ba, 0, ba.Length);

           tcpclnt.Close();
       }

       private delegate void AddListBoxItemDelegate(object item);



       private void AddListBoxItem(object item)
       {
           

           if (this.ConvBox.InvokeRequired)
           {
               // This is a worker thread so delegate the task.
               this.ConvBox.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item);
           }
           else
           {
               // This is the UI thread so perform the task.
               this.ConvBox.Items.Add(item);
           }
       }

       private void SendButton_Click(object sender, EventArgs e)
       {
           SendMessages(MessagesBox.Text);
       }

       private void ConvLabel_Click(object sender, EventArgs e)
       {

       }

       private void label1_Click(object sender, EventArgs e)
       {

       }

       private void ConvBox_SelectedIndexChanged(object sender, EventArgs e)
       {

       }
    }
}

Recommended Answers

All 3 Replies

Change this method to:

private void AddListBoxItem(object item)
       { 
           if (this.ConvBox.InvokeRequired)
               this.ConvBox.Invoke(new AddListBoxItemDelegate(AddListBoxitem), new object[] {item});
           else
               this.ConvBox.Items.Add(item);
       }

Thanks soo much for helping me!

but, no change. Same issue.

UPDATE: nevermind, i fixed it! i needed to include the creation of the tcplistener in the dowhile loop. i think i understand why that was the problem, but any expert care to explain precisely what was happening/why that fixed it ?

Hi rootchord

Have you Solved it??

The above Exception states that the window handle should be created for that form..

I have come across the same Exception and i cleared it by creating a window handle!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.