The MSDN contains a good article with examples about using control methods and properties from other threads.
In short, what you need is a delegate method that sets the Text
property of your text box with a given string. You then call that delegate from within your mySerialPort_DataReceived
handler via the TextBox.Invoke()
method. Something like this:
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
private void Form1_Load(object sender, EventArgs e)
{
//...
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
textbox1.AppendText(myString);
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string s= sp.ReadExisting();
textbox1.Invoke(this.myDelegate, new Object[] {s});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…