这是完整的程序代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace DeviceApplication4
{
public partial class Form1 : Form
{
SerialPort ComPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SendData("1");
this.label1.Text = "我按了第一个按钮";
}
private void button2_Click(object sender, EventArgs e)
{
SendData("2");
this.label1.Text = "我按了第二个按钮";
}
private void button3_Click(object sender, EventArgs e)
{
SendData("3");
this.label1.Text = "我按了第三个按钮";
}
private void button4_Click(object sender, EventArgs e)
{
SendData("4");
this.label1.Text = "我按了第四个按钮";
}
private void Form1_Load(object sender, EventArgs e)
{
ComOpen();
ComPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}
//发送数据
private void SendData(string s)
{
if (ComPort.IsOpen == true) ComPort.Close();
try
{
ComPort.Open();
if (ComPort.IsOpen)//检查串口是否打开
{
// 发送用户的文本到串口
ComPort.Write(s);
}
else
{
MessageBox.Show("可能串口没有打开!", "提示");
}
}
catch
{
MessageBox.Show("出现异常请重新启动程序!", "提示");
}
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 读取缓冲区的数据
string data = ComPort.ReadExisting();
// 显示读取的数据到数据窗口
updateReceiveText(data);
}
public void updateReceiveText(string msg)
{
this.textBox1.Invoke(new EventHandler(delegate
{
//this.textBox1.AppendText(msg);
this.textBox1.Text = this.textBox1.Text + msg;
this.textBox1.ScrollToCaret();
}));
}
private void ComOpen()
{
if (ComPort.IsOpen == true) ComPort.Close();
// 打开串口
try
{
ComPort.Open();
}
catch
{
MessageBox.Show("没有发现此串口或串口可能被占用!", "提示");
}
}
private void button5_Click(object sender, EventArgs e)
{
this.textBox1.Text = " ";
}
}
}