c#桌面应用开发
1、环境搭建和工程创建:参照番茄定时器项目
2、界面布局设计
3、具体功能函数
(1)端口扫描:
c#
private void btn_com_scan_Click(object sender, EventArgs e)
{
//端口号扫描
ReflashPortToComboBox(serialPort1, cb_select_com);
}
(2)初始化界面数据设置
c#
private void Form1_Load(object sender, EventArgs e)
{
//第一次加载的时候,进行端口号扫描
ReflashPortToComboBox(serialPort1, cb_select_com);
cb_select_com.SelectedItem = "COM1";
cb_select_baudrate.SelectedItem = "115200";
cb_select_data_bits.SelectedItem = "8";
cb_select_check_bit.SelectedItem = "None";
cb_select_stop_bit.SelectedItem = "1";
btn_open_com.Enabled = true;
btn_close_com.Enabled = false;
//默认使用 ascii模式
rbtn_recv_ascii.Checked = true;
rbtn_send_ascii.Checked = true;
}
(3)串口接收:
c#
private void ReceiveData(object sender, SerialDataReceivedEventArgs e)
{
string content = serialPort1.ReadExisting(); //从串口中读取输入流,返回string
ShowData(content);
}
private void ShowData(string text)
{
string receiveText = text;
//更新接收数据计数
recv_cntr += (UInt32)receiveText.Length;
lab_recv_cntr.Text = recv_cntr.ToString();
textBox_debug.AppendText("接收到了"+ receiveText.Length.ToString()+ "个数据: "+ text+"\r\n");
if (rbtn_recv_hex.Checked)
{//按HEX模式 展示接收到的内容
byte[] recData = System.Text.Encoding.Default.GetBytes(receiveText);// 将接受到的字符串据转化成数组;
foreach (byte str in recData)
{
textBox_recv.AppendText(string.Format("{0:X2} ", str));
}
}
else
{//按ASCII模式 展示接收到的内容
textBox_recv.AppendText(text); //将收到的字符串追加展示出来
}
}
(4)按钮事件:
c#
private void btn_open_com_Click(object sender, EventArgs e)
{
Int32 ibaudrate = Convert.ToInt32(cb_select_baudrate.SelectedItem.ToString());
serialPort1.PortName = cb_select_com.SelectedItem.ToString();
serialPort1.BaudRate = ibaudrate;
serialPort1.Parity = (System.IO.Ports.Parity)Enum.Parse(typeof(System.IO.Ports.Parity), cb_select_check_bit.Text);
serialPort1.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits), cb_select_stop_bit.Text);
serialPort1.DataBits = Convert.ToInt16(cb_select_data_bits.Text);
//添加串口事件处理
serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(ReceiveData);
try
{
serialPort1.Open();
btn_open_com.Enabled = false;
btn_close_com.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show("串口打开失败"+ex, "Error");
}
4、完整工程代码开源
源码打包上传在CSDN,本意是不需要使用积分免费下载,如果下载时遇到收积分,联系我私发即可