先拖一个串口控件serialPort1
发送:
///
///串口打开
///
///
///
///
///
///
publicvoidSendPort(stringHospitalName)
{
byte[]TEMPBYTE=Encoding.ASCII.GetBytes(HospitalName);
this.serialPort1.Write(TEMPBYTE,0,TEMPBYTE.Length);
}
serialPort1.Dispose();
serialPort1.PortName="串口号";(如:COM1)
if(serialPort1.IsOpen)serialPort1.Close();
try
{
serialPort1.Open();
SendPort("发送内容");
}
catch
{
//stsStatus.Text="Selectserialport!";
}
接收:
privatevoidserialPort1_DataReceived(objectsender,SerialDataReceivedEventArgse)
{
textBox6.Text="";
intbytes=serialPort1.BytesToRead;
byte[]buffer=newbyte[bytes];
if(bytes==0)
{
return;
}
serialPort1.Read(buffer,0,bytes);
textBox6.Text=Encoding.ASCII.GetString(buffer);//textBox6.Text显示接收的内容
}
|
|