实例介绍
【实例简介】实现串口调试
【实例截图】
【核心代码】
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;
using System.Runtime.InteropServices;
namespace 串口调试器
{
public partial class Form1 : Form
{
//hotkeyWinapi声明:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
SerialPort sp = new SerialPort(); //声明串口类
bool stoptb2 = false;
//发送字节计数
int fscout = 0;
//接收字节计数
int jscout = 0;
//十六进制显示标志
bool ishex = false;
//委托
delegate void HandleInterfaceUpdateDelegate(string text); //委托,此为重点
HandleInterfaceUpdateDelegate interfaceUpdateHandle = null;
public Form1()
{
InitializeComponent();
}
//重载函数
protected override void WndProc(ref Message m)
{
//
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY)
{
int id = m.WParam.ToInt32();
//Ctrl Z
Byte[] byte1 = new Byte[1];
byte1[0] = 0x1A;
if (id == 100)
{
if (sp.IsOpen == true)
{
sp.Write(byte1, 0, 1);
}
}
}
base.WndProc(ref m);
}
private void Form1_Load(object sender, EventArgs e)
{
//初始化状态栏
toolStripStatusLabel1.Text = "串口调试器正在初始化 ";
//热键注册Ctrl Alt Z
RegisterHotKey(this.Handle, 100, 6, Convert.ToUInt32(Keys.Z));
//初始化combox1
foreach (string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
//初始化combox2
comboBox2.Items.Add("300");
comboBox2.Items.Add("600");
comboBox2.Items.Add("1200");
comboBox2.Items.Add("2400");
comboBox2.Items.Add("4800");
comboBox2.Items.Add("9600");
comboBox2.Items.Add("19200");
comboBox2.Items.Add("38400");
comboBox2.Items.Add("76800");
comboBox2.Items.Add("115200");
comboBox2.SelectedIndex = 5;
//初始化combox3
comboBox3.Items.Add("None");
comboBox3.Items.Add("Odd");
comboBox3.Items.Add("Even");
comboBox3.SelectedIndex = 0;
//初始化combox4
comboBox4.Items.Add("8");
comboBox4.Items.Add("7");
comboBox4.Items.Add("6");
comboBox4.SelectedIndex = 0;
//初始化combox5
comboBox5.Items.Add("1");
comboBox5.Items.Add("2");
comboBox5.SelectedIndex = 0;
//textbox1初始化
textBox1.Text = "1000";
//有串口
if (comboBox1.Items.Count > 0)
{
comboBox1.SelectedIndex = 0;
//串口变量初始化
sp.PortName = comboBox1.SelectedItem.ToString();
sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
sp.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
sp.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
sp.RtsEnable = true;
sp.ReceivedBytesThreshold = 1;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数
sp.DataReceived = new System.IO.Ports.SerialDataReceivedEventHandler(this.sp_DataReceived); //DataReceived事件委托
}
else
{
label9.Text = "未检测到串口";
label9.ForeColor = Color.Red;
}
//委托实例化
interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox); //实例化委托对象
//初始化状态栏
toolStripStatusLabel1.Text = "串口调试器初始化成功 ";
}
//委托的函数
private void UpdateTextBox(string text)
{
if (stoptb2 == false)
{
textBox3.Text = text;
}
//更新接收显示
toolStripStatusLabel3.Text = String.Format(" 接收:{0} 字节 ", jscout);
}
//DataReceived事件委托方法
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int readlen = sp.BytesToRead;
//接收计数
jscout = readlen;
byte[] readBuffer = new byte[sp.ReadBufferSize];
sp.Read(readBuffer, 0, readBuffer.Length);
if (ishex)
{
string readbuf = null;
//十六进制格式化数据
for(int i=0;i<readlen;i )
{
string s = String.Format("{0:X}", Convert.ToInt32(readBuffer[i]));
if (s.Length > 1)
{
readbuf = s " ";
}
else
{
readbuf = "0" s " ";
}
}
this.Invoke(interfaceUpdateHandle, readbuf);
}
else
{
this.Invoke(interfaceUpdateHandle, new string[] { Encoding.UTF8.GetString(readBuffer) });
}
}
private void button1_Click(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
try
{
sp.Open();
//清空缓冲区
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
}
catch (Exception)
{
label9.Text = "串口无法连接";
return;
}
button1.Text = "断开串口";
label6.Text = "已连接";
label6.ForeColor = Color.Green;
label9.Text = sp.PortName "," sp.BaudRate "," sp.Parity "," sp.DataBits "," sp.StopBits;
//改变状态栏
toolStripStatusLabel1.Text = " " label9.Text " ";
}
else
{
if (checkBox2.Checked)
{
MessageBox.Show("正在发送,请先停止自动发送");
return;
}
sp.Close();
label6.Text = "已断开";
label6.ForeColor = Color.Red;
label9.Text = " 串口关闭状态";
button1.Text = "连接串口";
//改变状态栏
toolStripStatusLabel1.Text = "串口关闭状态 不能操作串口";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (stoptb2 == false) //停止显示标志置位
{
stoptb2 = true;
button2.Text = "继续显示";
}
else
{
stoptb2 = false; //停止显示标志复位
button2.Text = "停止显示";
}
}
private void button3_Click(object sender, EventArgs e)
{
textBox3.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
if (sp.IsOpen == true)
{
fscout = textBox2.Text.Length;
sp.Write(textBox2.Text);
toolStripStatusLabel2.Text = String.Format(" 发送:{0} 字节 ", fscout);
}
else
{
MessageBox.Show("串口未打开");
}
}
private void button5_Click(object sender, EventArgs e)
{
fscout = 0;
toolStripStatusLabel2.Text = " 发送:0 字节 ";
}
private void button6_Click(object sender, EventArgs e)
{
jscout = 0;
toolStripStatusLabel3.Text = " 接收:0 字节 ";
}
private void button7_Click(object sender, EventArgs e)
{
About abFrm = new About();
abFrm.Owner = this;
abFrm.ShowDialog();
}
//程序退出
private void button8_Click(object sender, EventArgs e)
{
UnregisterHotKey(this.Handle, 100);
sp.Close();
this.Close();
}
//combox1改变
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
sp.PortName = comboBox1.SelectedItem.ToString();
}
}
//combox2改变
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
}
//combox3改变
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
sp.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
}
//combox4改变
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
sp.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
}
//combox5改变
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
ishex = true;
}
else
{
ishex = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sp.IsOpen == true)
{
fscout = textBox2.Text.Length;
sp.Write(textBox2.Text);
toolStripStatusLabel2.Text = String.Format(" 发送:{0} 字节 ", fscout);
}
else
{
MessageBox.Show("串口未打开");
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
checkBox2.Checked = false;
}
else
{
timer1.Enabled = checkBox2.Checked;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == null||textBox1.Text=="")
{
timer1.Interval = 1000;
}
else
{
timer1.Interval = Convert.ToInt32(textBox1.Text);
}
}
private void checkBox2_Click(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
MessageBox.Show("串口未连接");
}
}
}
}
好例子网口号:伸出你的我的手 — 分享!
网友评论
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


支持(0) 盖楼(回复)