Kod: Markera allt
// we want to have the serial port thread report back data received, but to display
// that data we must create a delegate function to show the data in the richTextBox
// define the delegate
public delegate void SetText();
// define an instance of the delegate
SetText setText;
// create a string that will be loaded with the data received from the port
public string str = "";
// note that this function runs in a separate thread and thus we must use a delegate in order
// to display the results in the richTextBox.
//void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
//private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// instantiate the delegate to be invoked by this thread
setText = new SetText(mySetText);
// load the data into the string
try
{
str = serialPort1.ReadExisting();
}
catch (System.Exception ex)
{
MessageBox.Show("Error - port_DataReceived Exception: " + ex);
}
// invoke the delegate in the MainForm thread
this.Invoke(setText);
}
// create the instance of the delegate to be used to write the received data to the richTextBox
public void mySetText()
{
// show the text
richTextBox2.Text += str.ToString();
moveCaretToEnd();
}
// This rigaramole is needed to keep the last received item displayed
// it kind of flickers and should be fixed
private void richTextBoxReceive_TextChanged(object sender, System.EventArgs e)
{
moveCaretToEnd();
}
private void moveCaretToEnd()
{
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.SelectionLength = 0;
richTextBox1.ScrollToCaret();
}
#endregion
}