serialPort Questions
I tried unsuccessfully to use the DataReceived event to read data from the serial port. It gives a thread exception and I cannot figure out what the error message is trying to tell me. So I put a button on the form and added:
| | privatevoid button2_Click(object sender, EventArgs e) { while (serialPort1.BytesToRead > 0) { char[] c =newchar[serialPort1.BytesToRead];for (int i = 0; i < serialPort1.BytesToRead; i++) { c[ i ] = (char)serialPort1.ReadByte(); richTextBox1.Text += c[ i ].ToString(); } } }
|
Which is a newbie hack kludge if I've ever seen one. Surely there is a better way.First: Am I going to have to poll to receive serialPort data? How do I use the DataReceived event?
Second: Has anyone gotten the ReadByte or ReadChar to directly load the text in a text box? And if so, how so?
Third: How do I copy code from VS and past it in here and not have to reformat? The C# button just makes the unformated code even uglier.
Thanks
Joe
You may have a problem with the event being thrown in the context of the running thread, rather than the GUI thread. This is an error in the component you're using, but you can get around it with this.
Try:
| | if (this.InvokeRequired) { this.Invoke(new EventHandler(theMethodName), new object[] { theParameters, anotherParameter, asManyAsNeeded, orYouCanHaveJustOneInHere }); } else { //Your code here } |
I am having the same problem, but there is no InvokeRequired in the compact framework I am working with.. see my problem here:
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=16634
Do you have any suggestions?
--Jason