I need to read data from COM
in Form1
and then In Form2
again too.
What will be the best way?
In Form1
read the COM
data, then mySerialPort.Close();
, and in Form2
open new connection?
If like this, where in my code above should I close
it?
Or don't close the COM
? If don't close, how can I read the data in Form2
?
namespace portreader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
SerialPort mySerialPort = new SerialPort();
mySerialPort.PortName = "COM3";
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
mySerialPort.Open();
}
string _buffer;
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (this.InvokeRequired)
{
// Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
this.BeginInvoke(new EventHandler<SerialDataReceivedEventArgs>(mySerialPort_DataReceived), new object[] { sender, e });
return;
}
SerialPort sp = (SerialPort)sender;
string data = sp.ReadExisting();
_buffer += data;
if (_buffer.Length >= 8)
{
int chipnumber = Int32.Parse(_buffer, System.Globalization.NumberStyles.HexNumber);
Form2 form2 = new Form2(chipnumber);
form2.ShowDialog(this);
_buffer = null;
}
}
}
}