Redgum
Привет,
Это старый и часто задаваемый вопрос. Вы видите, что ваши данные из последовательного порта принимаются в другом потоке. Поток, который запускает пользовательский интерфейс Windows, отличается. Это как две разные машины, работающие в одном доме, но одна понятия не имеет, как обращаться с другой.
Поэтому вам нужен так называемый делегат.
Смотрите код ниже.
// I've named this 'StringDelegate' - returns void and carries a string.
delegate void StringDelegate(string text);
// Look at your rich text box, use the rich text box control's
// name property in place where I have written 'richTextBox1'
//
// Call this method directly with the
// data from your Serial port.
//
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.richTextBox1.InvokeRequired)
{
StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.richTextBox1.Text = text;
}
}