以下是【SerialPort】控件的使用實例,發送端和接收端代碼除了端口號(例:“COM9”)不同,其他都一樣:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace Test_Serialport_串口控件_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SerialPort port1;
string strCom = "COM9";
private delegate void ShowDelegate(string strshow);
private void Form1_Load(object sender, EventArgs e)
{
//我現在用的COM1端口,按需要可改成COM2,COM3
InitCOM(strCom);
OpenPort();
//this.txtReceive.InvokeRequired = true;
}
//初始化SerialPort對象方法.PortName爲COM口名稱,例如"COM1","COM2"等,注意是string類型
public void InitCOM(string PortName)
{
port1 = new SerialPort(PortName);
port1.BaudRate = 9600;//波特率
port1.Parity = Parity.None;//無奇偶校驗位
port1.StopBits = StopBits.Two;//兩個停止位
port1.Handshake = Handshake.RequestToSend;//控制協議
port1.ReceivedBytesThreshold = 1;//設置 DataReceived 事件發生前內部輸入緩衝區中的字節數
port1.DataReceived += new SerialDataReceivedEventHandler(port1_DataReceived);//DataReceived事件委託
}
//DataReceived事件委託方法
private void port1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
StringBuilder currentline = new StringBuilder();
//循環接收數據
while (port1.BytesToRead > 0)
{
char ch = (char)port1.ReadByte();
currentline.Append(ch);
}
//在這裏對接收到的數據進行處理
ShowTxt(currentline.ToString());
//this.txtReceive.Text = currentline.ToString();
//
currentline = new StringBuilder();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
public void ShowTxt(string strShow)
{
if (this.txtReceive.InvokeRequired)
{
// this.txtreceive.BeginInvoke(new ShowDelegate(Show), strshow);//這個也可以
this.txtReceive.Invoke(new ShowDelegate(ShowTxt), strShow);
}
else
{
this.txtReceive.Text = strShow;
}
}
//打開串口的方法
public void OpenPort()
{
try
{
port1.Open();
if (port1.IsOpen)
{
Console.WriteLine("the port is opened!");
this.labStat.Text = strCom + " 已連接!";
}
else
{
Console.WriteLine("failure to open the port!");
this.labStat.Text = "連接失敗!";
}
}
catch { }
}
//關閉串口的方法
public void ClosePort()
{
port1.Close();
if (!port1.IsOpen)
{
Console.WriteLine("the port is already closed!");
}
}
//向串口發送數據
public void SendCommand(string CommandString)
{
byte[] WriteBuffer = Encoding.ASCII.GetBytes(CommandString);
port1.Write(WriteBuffer, 0, WriteBuffer.Length);
}
//調用實例
private void btnSend_Click(object sender, EventArgs e)
{
string str = this.txtSend.Text;
SendCommand(str);
}
private void timer1_Tick(object sender, EventArgs e)
{
labTime.Text = "當前時間是:" + DateTime.Now.ToLongTimeString();
}
}
}