码迷,mamicode.com
首页 > Windows程序 > 详细

C#串口通讯实例

时间:2017-04-24 15:47:17      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:led   空间   draw   gen   gets   private   linq   rms   name   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;//新调用的类所在的命名空间

namespace chuankou
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//发送按钮的响应时间
private void button1_Click_1(object sender, EventArgs e)
{
//对于中文的话,要先对其进行编码,将其转换成 _Base64String ,否则你得不到中文字符串的
byte[] data = Encoding.Unicode.GetBytes(richTextBox1.Text);
string str = Convert.ToBase64String(data);
sPort.WriteLine(str);
MessageBox.Show("数据发送成功", "系统提示");
richTextBox2.Text = Encoding.Unicode.GetString(data)+"\r\n";
button1.Enabled = false;
button2.Enabled = true;
}
private void button2_Click_1(object sender, EventArgs e)
{
//解码然后将字符串赋值给 文本框的 文本区
//byte[] data = Convert.FromBase64String(sPort.ReadLine());
//richTextBox2.Text = Encoding.Unicode.GetString(data);
//对于中文的话,要先对其进行编码,将其转换成 _Base64String ,否则你得不到中文字符串的
byte[] data = Encoding.Unicode.GetBytes(richTextBox2.Text);
string str = Convert.ToBase64String(data);
sPort.WriteLine(str);
MessageBox.Show("数据发送成功", "系统提示");
richTextBox1.Text = Encoding.Unicode.GetString(data)+"\r\n";
button1.Enabled = true;
button2.Enabled = false;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void Form1_Load_1(object sender, EventArgs e)
{
sPort.PortName = "COM1";//串口的portname
sPort.BaudRate = 9600;//串口的波特率
sPort.Open();
}
private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
{
//关闭串口
sPort.Close();
}
}
}

 

技术分享

C#串口通讯实例

标签:led   空间   draw   gen   gets   private   linq   rms   name   

原文地址:http://www.cnblogs.com/wuxiaochao/p/6757104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!