我需要從COM
中讀取Form1
然後再在Form2
中的數據。C#Com端口關閉
什麼將是最好的方法?
在Form1
讀取COM
數據,然後mySerialPort.Close();
,並在Form2
打開新的連接?
如果這樣,在我的代碼上面我應該在哪裏close
呢?
還是不要關閉COM
?如果不關閉,我怎樣才能讀取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;
}
}
}
}
就我個人而言,我會創建一個專門處理應用程序的通信端口通信的類,並且兩種表單都使用該類。 – itsme86