namespace 串口实例
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSend_Click(object sender, EventArgs e)
{
//手动发送
SendMsg();
}
private void SendMsg()
{
this.serialPort1.Write(this.txtSend.Text);
}
#region 控制输入数字
private void ComboBox_TextUpdate(object sender, EventArgs e)
{
ComboBox cbo = sender as ComboBox;
int n;
if (!int.TryParse(cbo.Text, out n))
{
cbo.Text = cbo.Text.Substring(0, cbo.Text.Length - 1);
}
else
{
if (n <= 0)
{
cbo.Text = cbo.Text.Substring(0, cbo.Text.Length - 1);
}
}
}
private void txtTime_TextChanged(object sender, EventArgs e)
{
TextBox text = sender as TextBox;
int n;
if (!int.TryParse(text.Text, out n))
{
text.Text = text.Text.Substring(0, text.Text.Length - 1);
}
else
{
if (n <= 0)
{
text.Text = text.Text.Substring(0, text.Text.Length - 1);
}
else
{
this.timer1.Interval = n;
}
}
}
#endregion
///
/// 清空显示文本框
///
///
///
private void btnClear_Click(object sender, EventArgs e)
{
this.txtRecive.Clear();
}
private void timer1_Tick(object sender, EventArgs e)
{
SendMsg();
}
private void cbtSend_CheckedChanged(object sender, EventArgs e)
{
CheckBox check = sender as CheckBox;
if (check.Checked)
{
this.timer1.Start();
}
else
{
this.timer1.Stop();
}
}
///
/// 接收返回的数据
///
///
///
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string a="";
if (this.cbkShow16.Checked)
{
//十六进制显示
a = this.serialPort1.ReadExisting();
}
else
{
//字符串显示
byte[] by = new byte[this.serialPort1.BytesToRead];
this.serialPort1.Read(by, 0, this.serialPort1.BytesToRead);
a = Encoding.ASCII.GetString(by);
}
this.txtRecive.AppendText(a);
this.txtRecive.ScrollToCaret();
}
private void Form1_Load(object sender, EventArgs e)
{
//加载
this.serialPort1.RtsEnable = true;
button1_Click(this.btnOpen, null);
}
private void button1_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.Text == "打开端口")
{
try
{
this.serialPort1.PortName = this.cboPortName.Text;
this.serialPort1.BaudRate = Convert.ToInt32(this.cboRaudRate.Text);
this.serialPort1.DataBits = Convert.ToInt32(this.cboDataBits.Text);
this.serialPort1.ReceivedBytesThreshold = Convert.ToInt32(this.cboReceivedBytesThreshold.Text);
this.serialPort1.Open();
btn.Text = "关闭端口";
}
catch
{
MessageBox.Show("打开端口失败,请检查端口是否被占用.");
}
}
else
{
this.serialPort1.Close();
btn.Text = "打开端口";
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
this.serialPort1.Close();
}
catch
{
}
}
}
}
1