#region Namespace Inclusionsusing System;using System.Data;using System.Text;using System.Drawing;using System.IO.Ports;using System.Windows.Forms;using System.ComponentModel;using System.Collections.Generic;using SerialPortTerminal.Properties;#endregionnamespace SerialPortTerminal{ #region Public Enumerations public enum DataMode { Text, Hex } public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error }; #endregion public partial class frmTerminal : Form { #region Local Variables // The main control for communicating through the RS-232 port private SerialPort comport = new SerialPort(); // Various colors for logging info private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red }; // Temp holder for whether a key was pressed private bool KeyHandled = false; #endregion #region Constructor public frmTerminal() { // Build the form InitializeComponent(); // Restore the users settings InitializeControlValues(); // Enable/disable controls based on the current state EnableControls(); // When data is recieved through the port, call this method comport.DataReceived = new SerialDataReceivedEventHandler(port_DataReceived); } #endregion #region Local Methods /// <summary> Save the user's settings. </summary> private void SaveSettings() { Settings.Default.BaudRate = int.Parse(cmbBaudRate.Text); Settings.Default.DataBits = int.Parse(cmbDataBits.Text); Settings.Default.DataMode = CurrentDataMode; Settings.Default.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text); Settings.Default.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text); Settings.Default.PortName = cmbPortName.Text; Settings.Default.Save(); } /// <summary> Populate the form's controls with default settings. </summary> private void InitializeControlValues() { cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity))); cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits))); cmbParity.Text = Settings.Default.Parity.ToString(); cmbStopBits.Text = Settings.Default.StopBits.ToString(); cmbDataBits.Text = Settings.Default.DataBits.ToString(); cmbParity.Text = Settings.Default.Parity.ToString(); cmbBaudRate.Text = Settings.Default.BaudRate.ToString(); CurrentDataMode = Settings.Default.DataMode; cmbPortName.Items.Clear(); foreach (string s in SerialPort.GetPortNames()) cmbPortName.Items.Add(s); if (cmbPortName.Items.Contains(Settings.Default.PortName)) cmbPortName.Text = Settings.Default.PortName; else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = 0; //else //{ // MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error); // this.Close(); //} } /// <summary> Enable/disable controls based on the app's current state. </summary> private void EnableControls() { // Enable/disable controls based on whether the port is open or not gbPortSettings.Enabled = !comport.IsOpen; txtSendData.Enabled = btnSend.Enabled = comport.IsOpen; if (comport.IsOpen) btnOpenPort.Text = "&Close Port"; else btnOpenPort.Text = "&Open Port"; } /// <summary> Send the user's data currently entered in the 'send' box.</summary> private void SendData() { if (CurrentDataMode == DataMode.Text) { // Send the user's text straight out the port byte[] senddata = System.Text.Encoding.ASCII.GetBytes(txtSendData.Text "\r"); comport.Write(senddata, 0, senddata.Length); // Show in the terminal window the user's text //Log(LogMsgType.Outgoing, txtSendData.Text "\n"); rtfTerminal.AppendText("\r\n"); } else { try { // Convert the user's string of hex digits (ex: B4 CA E2) to a byte array byte[] data = HexStringToByteArray(txtSendData.Text); // Send the binary data out the port comport.Write(data, 0, data.Length); // Show the hex digits on in the terminal window //Log(LogMsgType.Outgoing, ByteArrayToHexString(data) "\n"); rtfTerminal.AppendText("\r\n"); } catch (FormatException) { // Inform the user if the hex string was not properly formatted Log(LogMsgType.Error, "Not properly formatted hex string: " txtSendData.Text "\n"); } } txtSendData.SelectAll(); } /// <summary> Log data to the terminal window. </summary> /// <param name="msgtype"> The type of message to be written. </param> /// <param name="msg"> The string containing the message to be shown. </param> private void Log(LogMsgType msgtype, string msg) { rtfTerminal.Invoke(new EventHandler(delegate { rtfTerminal.SelectedText = string.Empty; rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold); rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype]; rtfTerminal.AppendText(msg); rtfTerminal.ScrollToCaret(); })); } /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary> /// <param name="s"> The string containing the hex digits (with or without spaces). </param> /// <returns> Returns an array of bytes. </returns> private byte[] HexStringToByteArray(string s) { s = s.Replace(" ", ""); byte[] buffer = new byte[s.Length / 2]; for (int i = 0; i < s.Length; i = 2) buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16); return buffer; } /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary> /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param> /// <returns> Returns a well formatted string of hex digits with spacing. </returns> private string ByteArrayToHexString(byte[] data) { StringBuilder sb = new StringBuilder(data.Length * 3); foreach (byte b in data) sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' ')); return sb.ToString().ToUpper(); } #endregion #region Local Properties private DataMode CurrentDataMode { get { if (rbHex.Checked) return DataMode.Hex; else return DataMode.Text; } set { if (value == DataMode.Text) rbText.Checked = true; else rbHex.Checked = true; } } #endregion #region Event Handlers private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Show the user the about dialog (new frmAbout()).ShowDialog(this); } private void frmTerminal_Shown(object sender, EventArgs e) { Log(LogMsgType.Normal, String.Format("Application Started at {0}\n", DateTime.Now)); } private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e) { // The form is closing, save the user's preferences SaveSettings(); } private void rbText_CheckedChanged(object sender, EventArgs e) { if (rbText.Checked) CurrentDataMode = DataMode.Text; } private void rbHex_CheckedChanged(object sender, EventArgs e) { if (rbHex.Checked) CurrentDataMode = DataMode.Hex; } private void cmbBaudRate_Validating(object sender, CancelEventArgs e) { int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x); } private void cmbDataBits_Validating(object sender, CancelEventArgs e) { int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x); } private void btnOpenPort_Click(object sender, EventArgs e) { // If the port is open, close it. if (comport.IsOpen) comport.Close(); else { // Set the port's settings comport.BaudRate = int.Parse(cmbBaudRate.Text); comport.DataBits = int.Parse(cmbDataBits.Text); comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text); comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text); comport.PortName = cmbPortName.Text; // Open the port comport.Open(); } // Change the state of the form's controls EnableControls(); // If the port is open, send focus to the send data box if (comport.IsOpen) txtSendData.Focus(); } private void btnSend_Click(object sender, EventArgs e) { SendData(); } private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { string sdata; try { byte[] readBuffer = new byte[comport.ReadBufferSize]; comport.Read(readBuffer, 0, readBuffer.Length); sdata = System.Text.Encoding.Default.GetString(readBuffer); rtfTerminal.AppendText(sdata); } catch { } } private void txtSendData_KeyDown(object sender, KeyEventArgs e) { // If the user presses [ENTER], send the data now if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); } } private void txtSendData_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = KeyHandled; } #endregion }}
下载C#串口实例用户还喜欢
- 18480 文章数
- 500万+ 热度
作者专栏
编辑推荐
- 淡抹u2引擎,修复内容较多,物有所值
- 界域传说·经典巨作=传世单机(一键安装)
- 丸子版本(175个传世版本大集合)
- GS版本:神话公益服务端+客户端
- 图片放大工具(放大图片不模糊)
- 剪映无限制VIP版
- 传奇世界客户端下载器,史上最全传世客户端
- 传世GS20220920商业引擎注册+登录配置器 解压密码是1
- U2官方排行榜游戏网关 支持元神,支持传家宝
- GS开战传世客户端+服务端
- (淡漠夕阳)u2引擎合区工具
- 传世GS引擎消除“你的游戏客户端版本号过旧,请及时更新”提示
- 传世一机多区双线路配置器--免密码版本
- 传世凤凰登陆器劫持修复软件
- SQLite3 for Navicat
- 传奇世界npc对话框编辑工具
- 传世GS落霞铭文服务器端
- gs_20210409引擎包+注册机(无限制)
- 传奇世界NPC对话封包查看器[支持时长版和极速版]
- 彩虹引擎传世脚本编辑工具1.7版来了,支持函数脚本翻译
评论