using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Runtime.InteropServices;using System.Net.Sockets;using System.Net;using System.IO.Ports;using System.Threading;using System.IO;using System.Text .RegularExpressions ;namespace Ex13_01{ #region Public Enumerations public enum DataMode { Text, Hex } public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error }; #endregion public partial class Form1 : Form { public string ComValue; public string RESULT; public int Port; public Form1() { InitializeComponent(); Form.CheckForIllegalCrossThreadCalls = false; } private void Form1_Load(object sender, EventArgs e) { //read(); m_sp.PortName = "COM1"; m_sp.BaudRate = 9600; //比特率 m_sp.DataBits = 8; m_sp.Parity = Parity.None; //校验位 m_sp.StopBits = StopBits.One; //停止位 m_sp.Handshake = Handshake.None; listView_Chat.View = View.Details; listView_Chat.GridLines = true; listView_Chat.Columns.Add("Chat", 188, HorizontalAlignment.Center); listView_Chat.Columns.Add("Time", 113, HorizontalAlignment.Center); comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames()); } private void btnsend_Click_1(object sender, EventArgs e) //发送消息 { string senStr; senStr = textBox1.Text; try { //SendMsg(senStr); m_sp.Write(senStr); Message_Blue(senStr); } catch (Exception) { Message_Red("发送失败"); } if (listView_Chat.Items.Count > 16) { listView_Chat.Items.Clear(); } } public void Message_Red(string Message) //红色字体消息 { ListViewItem Show_Red = new ListViewItem(Message); Show_Red.ForeColor = Color.Red; listView_Chat.Items.Insert(0, Show_Red); Show_Red.SubItems.Add(DateTime.Now.ToString()); Show_Red.SubItems.Add("OK"); } public void Message_Blue(string Message) //蓝色字体消息 { ListViewItem Show_Blue = new ListViewItem(Message); Show_Blue.ForeColor = Color.Blue; listView_Chat.Items.Insert(0, Show_Blue); Show_Blue.SubItems.Add(DateTime.Now.ToString()); Show_Blue.SubItems.Add("OK"); } public void SendMsg(string senStr) // //发送消息 { if (m_sp.IsOpen) { byte[] data = Encoding.Default.GetBytes(senStr); string str = Encoding.Default.GetString(data); m_sp.WriteLine(str); Message_Blue(str); } else { m_sp.Open(); byte[] data = Encoding.Default.GetBytes(senStr); string str = Encoding.Default.GetString(data); m_sp.WriteLine(str); Message_Blue(str); } } private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { RESULT = comboBox1.Text; } private void ComChoose() //选择串口 { if (comboBox1.Text == "COM1") { Port = 1; } if (comboBox1.Text == "COM2") { Port = 2; } } private void btnopen_Click(object sender, EventArgs e) //打开串口 { if (m_sp.IsOpen == false) { m_sp.Open(); Message_Blue("串口打开成功"); } else { Message_Blue("串口已打开"); } } private void btnclose_Click(object sender, EventArgs e) //关闭串口 { if (m_sp.IsOpen == true) { m_sp.Close(); Message_Blue("串口关闭成功"); } else { Message_Blue("串口已关闭"); } } private void txtReceive_TextChanged(object sender, EventArgs e) { } private void listView_Chat_SelectedIndexChanged(object sender, EventArgs e) { } private void GetMessage_TextChanged(object sender, EventArgs e) { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void groupBox1_Enter(object sender, EventArgs e) { } //Thread _readThread; //线程读入 //bool _keepReading; //private void ReadPort() //{ // while (_keepReading) // { // if (m_sp.IsOpen) // {// byte[] readBuffer = new byte[m_sp.ReadBufferSize 1]; // try // { // byte[] data = new byte[m_sp.BytesToRead]; // int count = m_sp.Read(data, 0, m_sp.BytesToRead);//位移和長度超過陣列的界限或計數大於從索引至來源集合尾端的項目數。 // String SerialIn = System.Text.Encoding.Default.GetString(data, 0, count); // if (count != 0) // Message_Red(SerialIn); // } // catch (TimeoutException) // { } // } // else // { // TimeSpan waitTime = new TimeSpan(0,0,0,50); // Thread.Sleep(waitTime); // } // } //} private List<byte> buffer = new List<byte>(4096); private void m_sp_DataReceived(object sender, SerialDataReceivedEventArgs e) // 接收数据 { System.Threading.Thread.Sleep(100); SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.Write(indata); Message_Red(indata); if (listView_Chat.Items.Count > 16) { listView_Chat.Items.Clear(); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { m_sp.Close(); } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) textBox1.Focus(); } static DateTime Now; static DateTime End; int time; bool Show_One = true; public void TimeDlay(int Time) //延时 { try { time = int.Parse(textBox_Time.Text); End = DateTime.Now; if ((End - Now).TotalMilliseconds > Time) { step = 1; } } catch { if (Show_One == true) { Message_Red("检查发送间隔是否正确"); Show_One = false; } } } private void btnsend_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) btnsend.Focus(); } private void label1_Click(object sender, EventArgs e) { } private void checkBox_Auto_CheckedChanged(object sender, EventArgs e) { } bool Auto = true; int step; private void checkBox_Auto_Click(object sender, EventArgs e) { if (Auto == true) { step = 1; Auto = false; timer1.Enabled = true; } else { step = 0; Auto = true; } } private void timer1_Tick(object sender, EventArgs e) { switch (step) { case 0: break; case 1: //m_sp.WriteLine(textBox1.Text); //Message_Blue(textBox1.Text); SendMsg(textBox1.Text); step ; Now = DateTime.Now; break; case 2: TimeDlay(time); break; } } private void textBox_Time_TextChanged(object sender, EventArgs e) { } //public void Write(string path) //写入文本 //{ //FileStream fs = new FileStream(path, FileMode.Create); // StreamWriter sw = new StreamWriter(fs); // sw.Write(textBoxSave.Text); // sw.Flush();//清空缓冲区 // sw.Close();//关闭流 // fs.Close(); //} public void Write() //写入文本 { string text = textBoxSave.Text; if (text != null) { FileStream fs = new FileStream(@"C:\Documents and Settings\SHZBG-Auto\桌面\保存COM.txt", FileMode.Create); StreamWriter sw = new StreamWriter(fs); sw.Write("PortArgument=" textBoxSave.Text); sw.Flush();//清空缓冲区 sw.Close();//关闭流 fs.Close(); } else { Message_Red("请输入正确的数据!"); } } //public void read() //读取文本 //{ // //FileStream fs = new FileStream(@"C:\Documents and Settings\SHZBG-Auto\桌面\保存COM.txt", FileMode.Open); // StreamReader sw = new StreamReader(fs); // textBoxSave.Text = sw.ReadLine(); // sw.Close();//关闭流 // fs.Close(); // string[] x = Regex.Split(textBoxSave.Text, "PortArgument="); // foreach (string mr in x) // { // if (mr != null) // { // Message_Red(mr); // } // } //} private void btnSave_Click(object sender, EventArgs e) { //SaveFileDialog Filel = new SaveFileDialog(); //弹出窗口式写入 //Filel.Filter = "文本文件|*.txt"; //if (Filel.ShowDialog() == DialogResult.OK) //{ // StreamWriter sw = File.AppendText(Filel.FileName); // sw.Write(textBoxSave.Text); // sw.Flush();//清空缓冲区 // sw.Close();//关闭流 // //fs.Close(); //} Write(); } private void openFileDialog1_FileOk(object sender, CancelEventArgs e) { } private void saveFileDialog1_FileOk(object sender, CancelEventArgs e) { } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { } private void comboBox1_TextChanged(object sender, EventArgs e) { ComChoose(); string ComNumber = "COM" Port.ToString(); m_sp.PortName = ComNumber; } private void btnShow_Click(object sender, EventArgs e) { //read(); } private void textBox_TimeSave_TextChanged(object sender, EventArgs e) { } private void textBoxSave_TextChanged(object sender, EventArgs e) { } //private void btnSendFile_Click(object sender, EventArgs e) //{ // Byte[] arry = new byte[100]; // try // { // m_sp.Open(); // } // catch // { // Message_Red("打开失败"); // } // FileInfo file = new FileInfo(@"D:\zqq\发送.txt"); // FileStream send = new FileStream(@"D:\zqq\发送.txt", FileMode.Open, FileAccess.ReadWrite); // for (int i = 0; i < send.Length / 100; i ) // { // send.Read(arry, 0, 100); // System.Threading.Thread.SpinWait(250); // m_sp.Write(arry, 0, 100); // } // send.Read(arry, 0, (int)(send.Length % 100)); // m_sp.Write(arry, 0, (int)(send.Length % 100)); // m_sp.Close(); // send.Close(); //} //private void btnSelect_Click(object sender, EventArgs e) //{ // openFileDialog1.ShowDialog(); //} //private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e) //{ //} //private void openFileDialog1_FileOk(object sender, CancelEventArgs e) //{ // this.txtPath.Text = openFileDialog1.FileName; //} } }
下载C#通过串口读取和发送数据用户还喜欢
- 18480 文章数
- 500万+ 热度
作者专栏
编辑推荐
- 淡抹u2引擎,修复内容较多,物有所值
- 界域传说·经典巨作=传世单机(一键安装)
- 丸子版本(175个传世版本大集合)
- GS版本:神话公益服务端+客户端
- 图片放大工具(放大图片不模糊)
- 剪映无限制VIP版
- 传奇世界客户端下载器,史上最全传世客户端
- 传世GS20220920商业引擎注册+登录配置器 解压密码是1
- U2官方排行榜游戏网关 支持元神,支持传家宝
- GS开战传世客户端+服务端
- (淡漠夕阳)u2引擎合区工具
- 传世GS引擎消除“你的游戏客户端版本号过旧,请及时更新”提示
- 传世一机多区双线路配置器--免密码版本
- 传世凤凰登陆器劫持修复软件
- SQLite3 for Navicat
- 传奇世界npc对话框编辑工具
- 传世GS落霞铭文服务器端
- gs_20210409引擎包+注册机(无限制)
- 传奇世界NPC对话封包查看器[支持时长版和极速版]
- 彩虹引擎传世脚本编辑工具1.7版来了,支持函数脚本翻译
评论