I'm a beginner to serial port programming. I'm using following method in Form1.cs which reads some value from Serial Port.
Note: Port is managed in a singleton class and same object is being used across multiple classes
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
ComPort.DataReceived += SerialPortDataReceived;
}
private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
{
var serialPort = (SerialPort)sender;
data += serialPort.ReadExisting();
Console.WriteLine("DEBUG: Data=<" + data + ">");
SetText(data);
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
if (this.rtxtDataArea.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
if (text.Substring(text.Length - 2, 2) == "##")
{
Console.WriteLine("DEBUG: Substring= " + text.Substring(0, text.Length - 2));
if (text.Substring(0, text.Length - 2) == "OK##")
{
CheckForIllegalCrossThreadCalls = false;
MessageBox.Show("OK!!! You can login now", "Received Signal", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Hide();
Form2 frm2 = new Form2();
frm2.ShowDialog();
}
}
}
}
Now this function is working properly and I'm able to see proper output. But on Form2, I've another textbox where I need to receive inputs from Serial Port and when I try the same code on Form2.cs I get nothing in input. It seems that Form1.cs thread is blocking access.
I tried to close this port in Form1 but it just freezes the application.