关于VS.Net2005中串口操作说明(C#)(SerialPort组件) (转帖)

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;


namespace SerialPorts
{
    
public partial class frm_Main : Form
    {
        
#region Public Enumerations
        
public enum DataMode { Text, Hex }
        
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
        
#endregion
        
private Color[] LogMsgTypeColor = { Color.Orange, Color.Green, Color.Black, Color.Blue, Color.Red };


        
//禁用和启用程序中各控件的状态
        private void EnableControls()
        {
            
// 基于串口的打开与否,设置控件状态
            gbPortSettings.Enabled = !ComPort.IsOpen;
            btns.Enabled 
= btnstop.Enabled = txtSendData.Enabled = btnSend.Enabled = ComPort.IsOpen;

            
if (ComPort.IsOpen) btnOpenPort.Text = "关闭串口";
            
else btnOpenPort.Text = "打开串口";
        }
        
//初始化组件的数据,为串口提供相关参数
        private void InitializeControlValues()
        {
            cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(
typeof(Parity)));
            cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(
typeof(StopBits)));

            cmbPortName.Items.Clear();
            
foreach (string s in SerialPort.GetPortNames())
                cmbPortName.Items.Add(s);

            cmbPortName.Text 
= cmbPortName.Items[0].ToString();
            cmbParity.Text 
= cmbParity.Items[0].ToString();
            cmbStopBits.Text 
= cmbStopBits.Items[0].ToString();
            cmbDataBits.Text 
= cmbDataBits.Items[0].ToString();
            cmbParity.Text 
= cmbParity.Items[0].ToString();
            cmbBaudRate.Text 
= cmbBaudRate.Items[0].ToString();

            EnableControls();
        }
        
//十六进制转换字节数组
        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;
        }
        
//字节数组转换十六进制
        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();
        }
        
//显示数据日志
        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();
            }));
        }
        
//串口发送方式
        #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
        
//发送数据
        private void SendData()
        {
            
if (CurrentDataMode == DataMode.Text)
            {
                
// 发送用户的文本到串口
                ComPort.Write(txtSendData.Text);

                
// 将用户的文本显示到数据窗口
                Log(LogMsgType.Outgoing, txtSendData.Text + "\n");
            }
            
else
            {
                
try
                {
                    
// 转换用户十六进制数据到字节数组
                    byte[] data = HexStringToByteArray(txtSendData.Text);

                    
// 发送数据到串口
                    ComPort.Write(data, 0, data.Length);

                    
// 将用户十六进制数据到数据窗口
                    Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
                }
                
catch (FormatException)
                {
                    
// 转换错误
                    Log(LogMsgType.Error, "十六进制数据有误: " + txtSendData.Text + "\n");
                }
            }
            txtSendData.SelectAll();
        }


        
/// <summary>
        
/// -------------------------------------------------------------
        
/// </summary>
        public frm_Main()
        {
            InitializeComponent();
        }

        
private void Form1_Load(object sender, EventArgs e)
        {
            InitializeControlValues();
            ComPort.DataReceived 
+= new SerialDataReceivedEventHandler(port_DataReceived);
        }

        
//打开串口
        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            
if (ComPort.IsOpen) ComPort.Close();
            
else
            {
                
//设置串口参数
                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;

                
// 打开串口
                ComPort.Open();
            }

            
// 改变组件状态
            EnableControls();

            
// 如果串口打开,将焦点放入txtSendData
            if (ComPort.IsOpen) txtSendData.Focus();
        }

        
private void rbHex_CheckedChanged(object sender, EventArgs e)
        {
            
if (rbHex.Checked) CurrentDataMode = DataMode.Hex;
        }

        
private void rbText_CheckedChanged(object sender, EventArgs e)
        {
            
if (rbText.Checked) CurrentDataMode = DataMode.Text;
        }
        
//接收数据
        private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            

            
// 判断用户用的是字节模式还是字符模式
            if (CurrentDataMode == DataMode.Text)
            {
                
// 读取缓冲区的数据
                string data = ComPort.ReadExisting();

                
// 显示读取的数据到数据窗口
                Log(LogMsgType.Incoming, data + "\n");
            }
            
else
            {
                
// 获取字节长度
                int bytes = ComPort.BytesToRead;

                
// 创建字节数组
                byte[] buffer = new byte[bytes];

                
// 读取缓冲区的数据到数组
                ComPort.Read(buffer, 0, bytes);

                
// 显示读取的数据到数据窗口
                Log(LogMsgType.Incoming, ByteArrayToHexString(buffer) + "\n");
            }
        }
        
//发送数据按键
        private void btnSend_Click(object sender, EventArgs e)
        {
            SendData();
        }

        
private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            (
new frmAbout()).ShowDialog(this);
        }
        
//时间组件控制发送数据
        private void timer1_Tick(object sender, EventArgs e)
        {
            SendData();
        }
        
//连续发送数据
        private void button1_Click(object sender, EventArgs e)
        {
            delay.Enabled 
= true;
            btns.Enabled 
= !delay.Enabled;
            btnstop.Enabled 
= delay.Enabled;
        }
        
//停止连续发送数据
        private void button2_Click(object sender, EventArgs e)
        {
            delay.Enabled 
= false;
            btns.Enabled 
= !delay.Enabled;
            btnstop.Enabled 
= delay.Enabled;
        }
    }
}

 

posted @ 2010-06-07 15:58  逆时针  阅读(1109)  评论(0编辑  收藏  举报