c#读取COM端口


//初始化,打开/关闭端口
bool Init_SerialPort()
{
	bool temp = false;
	try
	{
		if (null == serialport)
		{
			serialport = new System.IO.Ports.SerialPort();
			serialport.PortName = "COM1";
			serialport.BaudRate = 9600;
			serialport.Parity = System.IO.Ports.Parity.None;
			serialport.DataBits = 8;
			serialport.StopBits = System.IO.Ports.StopBits.One;
			serialport.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff;
			serialport.ReceivedBytesThreshold = 6; //接收到6个字符才出发comPort_DataReceived
			serialport.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);
		}
		if (serialport.IsOpen)
		{
			serialport.Close();
			simpleButton1.Text = "端口已关闭!";
		}
		else
		{
			serialport.Open();
			simpleButton1.Text = "端口已打开!";
		}
		temp = true;
	}
	catch (Exception e)
	{
		//SetMsgText("COM口无效,无法打开COM!");
		MessageBox.Show("打开端口失败: " + e.Message);
	}
	return temp;
}

//端口扫描线程接收到数据
void comPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
	string dataReceived = serialport.ReadExisting();
	this.Invoke(new ShowDelegate(Show), dataReceived); //线程间调用,使用委托
}

//线程间调用,使用委托
private delegate void ShowDelegate(string dataReceived);

//主线程接收到数据
public void Show(string dataReceived)
{
	memoEdit1.Text = dataReceived;
}

你可能感兴趣的:(C#)