FlatStyle = System.Windows.Forms.FlatStyle.Popup;
this.button5.Location = new System.Drawing.Point(440, 504);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(64, 23);
this.button5.TabIndex = 9;
this.button5.Text = "关闭串口";
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(512, 533);
this.Controls.Add(this.button5);
this.Controls.Add(this.textBox8);
this.Controls.Add(this.label7);
this.Controls.Add(this.button4);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.button1);
this.Controls.Add(this.t_send);
this.Controls.Add(this.msg);
this.Controls.Add(this.label2);
this.Controls.Add(this.button3);
this.Name = "Form1";
this.Text = "串口通讯(小y设计)";
this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
//程序开启,串口初始化
private void Form1_Load(object sender, System.EventArgs e)
{
mycom1.PortNum=iPort;
mycom1.BaudRate=iRate;
mycom1.ByteSize=bSize;
mycom1.Parity=bParity;
mycom1.StopBits=bStopBits;
mycom1.ReadTimeout=iTimeout;
if(this.OpenCom())
msg.AppendText("串口初始化成功……\r\n");
else
msg.AppendText("串口初始化失败!\r\n");
}
//显示包信息
public string dis_package(byte[] reb)
{
string temp="";
foreach(byte b in reb)
temp+=b.ToString("X2")+" ";
return temp;
}
//开串口
public bool OpenCom()
{
try
{
if (mycom1.Opened)
{
mycom1.Close();
mycom1.Open(); //打开串口
}
else
{
mycom1.Open();//打开串口
}
return true;
}
catch(Exception e)
{
MessageBox.Show("错误:" + e.Message);
return false;
}
}
//发送按钮
private void button1_Click(object sender, System.EventArgs e)
{
if(t_send.Text=="")
{MessageBox.Show("发送数据为空!");return;}
byte[] temp1=mysendb();
int sendnumb=0;
try
{
sendnumb=mycom1.Write(temp1);
msg.AppendText("\r\n发送数据("+sendnumb+"):"+dis_package(temp1));
recb=mycom1.Read(50);
//if(recb.Length!=0)
msg.AppendText("\r\n接收到数据包:"+dis_package(recb));
}
catch
{msg.AppendText("\r\n发送失败!");return;}
//OpenCom();
}
//去掉发送数组中的空格
public string delspace(string putin)
{
string putout="";
for(int i=0;i {
if(putin[i]!=' ')
putout+=putin[i];
}
return putout;
}
//提取数据包
public byte[] mysendb()
{
string temps=delspace(t_send.Text);
byte[] tempb=new byte[50];
int j=0;
for(int i=0;i tempb[j]=Convert.ToByte(temps.Substring(i,2),16);
byte[] send=new byte[j];
Array.Copy(tempb,send,j);
return send;
}
//清空按钮
private void button3_Click(object sender, System.EventArgs e)
{
t_send.Text=string.Empty;
msg.Text=string.Empty;
}
//参数设置
private void button2_Click(object sender, System.EventArgs e)
{
mycom1.PortNum=Convert.ToInt16(t_port.Text); //1,2,3,4
mycom1.BaudRate=Convert.ToInt16(t_rate.Text); //1200,2400,4800,9600
mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10); //8 bits
mycom1.Parity=Convert.ToByte(t_parity.Te