标签:
串口在每个窗体打开关闭容易出现访问被拒绝情况,这个时候只能重启电脑重置解决.
所以比较好的方式是使用母窗体打开串口,然后子窗体调用,不会出现上诉问题.
调用方法:
1.母窗体
//打开SerialPort即可
private void button2_Click(object sender, EventArgs e)
{
serialPort1.BaudRate = 9600;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.PortName = "COM1";
serialPort1.Open();
}
//Show子窗体时候传入SerialPort
private void btnFirstDiBang_Click(object sender, EventArgs e)
{
FrmDiBangFirstInput frm = new FrmDiBangFirstInput();
frm._SerialPort = this.port;
frm._UserInfo = this._UserInfo;
frm.ShowDialog();
}
2.子窗体:
//把母窗体SerialPort传入
public SerialPort _SerialPort
{
get;
set;
}
//使用委托传值
private delegate void UpdateTextEventHandler(string text); //委托,此为重点
private UpdateTextEventHandler updateText;
private void UpdateTextBox(string text)
{
txtMaoZhong.Text = text;
}
//初始化时候绑定事件及实例化委托
this._SerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.port_DataReceived);//SerialPort绑定事件
updateText = new UpdateTextEventHandler(UpdateTextBox);//实例化委托对象,用来给TextBox赋值
//接收数据方法
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte[] readBuffer = new byte[_SerialPort.BytesToRead];
_SerialPort.Read(readBuffer, 0, readBuffer.Length);
string result = SerialPortProcess.GetBuffer(readBuffer).ToString();
//ConstParam.DiBangRead = result;
//
this.Invoke(updateText, new string[] { ConstParam.DiBangRead });
}
SerialPort串口多个窗体访问
标签:
原文地址:http://www.cnblogs.com/yuntianming/p/4600960.html