C#中的串口操作.docx
《C#中的串口操作.docx》由会员分享,可在线阅读,更多相关《C#中的串口操作.docx(16页珍藏版)》请在冰豆网上搜索。
C#中的串口操作
SerialPort编程(C#)SerialPort2008-12-2514:
20:
08阅读8760评论4字号:
大中小订阅
微软代码:
取出本机的COM端口字符串
publicstaticstring[]GetPortNames()
{
RegistryKeylocalMachine=null;
RegistryKeykey2=null;
string[]textArray=null;
//这里有个断言,判断该注册表项是否存在
newRegistryPermission(RegistryPermissionAccess.Read,@"HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM").Assert();
try
localMachine=Registry.LocalMachine;
key2=localMachine.OpenSubKey(@"HARDWARE\DEVICEMAP\SERIALCOMM",false);
if(key2!
=null)
string[]valueNames=key2.GetValueNames();
textArray=newstring[valueNames.Length];
for(inti=0;i{textArray[i]=(string)key2.GetValue(valueNames[i]);}}}finally{if(localMachine!=null){localMachine.Close();}if(key2!=null){key2.Close();}CodeAccessPermission.RevertAssert();}if(textArray==null){textArray=newstring[0];}returntextArray;}VS.NET2005中SerialPort控件操作详解(C#)usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.IO.Ports;namespaceSerialPorts{publicpartialclassfrm_Main:Form{#regionPublicEnumerationspublicenumDataMode{Text,Hex}publicenumLogMsgType{Incoming,Outgoing,Normal,Warning,Error};#endregionprivateColor[]LogMsgTypeColor={Color.Orange,Color.Green,Color.Black,Color.Blue,Color.Red};//禁用和启用程序中各控件的状态privatevoidEnableControls(){//基于串口的打开与否,设置控件状态gbPortSettings.Enabled=!ComPort.IsOpen;btns.Enabled=btnstop.Enabled=txtSendData.Enabled=btnSend.Enabled=ComPort.IsOpen;if(ComPort.IsOpen)btnOpenPort.Text="关闭串口";elsebtnOpenPort.Text="打开串口";}//初始化组件的数据,为串口提供相关参数privatevoidInitializeControlValues(){cmbParity.Items.Clear();cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));cmbStopBits.Items.Clear();cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));cmbPortName.Items.Clear();foreach(stringsinSerialPort.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();}//十六进制转换字节数组privatebyte[]HexStringToByteArray(strings){s=s.Replace("","");byte[]buffer=newbyte[s.Length/2];for(inti=0;ibuffer[i/2]=(byte)Convert.ToByte(s.Substring(i,2),16);returnbuffer;}//字节数组转换十六进制privatestringByteArrayToHexString(byte[]data){StringBuildersb=newStringBuilder(data.Length*3);foreach(bytebindata)sb.Append(Convert.ToString(b,16).PadLeft(2,'0').PadRight(3,''));returnsb.ToString().ToUpper();}//显示数据日志privatevoidLog(LogMsgTypemsgtype,stringmsg){rtfTerminal.Invoke(newEventHandler(delegate{rtfTerminal.SelectedText=string.Empty;rtfTerminal.SelectionFont=newFont(rtfTerminal.SelectionFont,FontStyle.Bold);rtfTerminal.SelectionColor=LogMsgTypeColor[(int)msgtype];rtfTerminal.AppendText(msg);rtfTerminal.ScrollToCaret();}));}//串口发送方式#regionLocalPropertiesprivateDataModeCurrentDataMode{get{if(rbHex.Checked)returnDataMode.Hex;elsereturnDataMode.Text;}set{if(value==DataMode.Text)rbText.Checked=true;elserbHex.Checked=true;}}#endregion//发送数据privatevoidSendData(){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();}//////-------------------------------------------------------------///publicfrm_Main(){InitializeComponent();}privatevoidForm1_Load(objectsender,EventArgse){InitializeControlValues();ComPort.DataReceived+=newSerialDataReceivedEventHandler(port_DataReceived);}//打开串口privatevoidbtnOpenPort_Click(objectsender,EventArgse){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),cmbPari
textArray[i]=(string)key2.GetValue(valueNames[i]);
}
finally
if(localMachine!
localMachine.Close();
key2.Close();
CodeAccessPermission.RevertAssert();
if(textArray==null)
textArray=newstring[0];
returntextArray;
VS.NET2005中SerialPort控件操作详解(C#)
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.IO.Ports;
namespaceSerialPorts
publicpartialclassfrm_Main:
Form
#regionPublicEnumerations
publicenumDataMode{Text,Hex}
publicenumLogMsgType{Incoming,Outgoing,Normal,Warning,Error};
#endregion
privateColor[]LogMsgTypeColor={Color.Orange,Color.Green,Color.Black,Color.Blue,Color.Red};
//禁用和启用程序中各控件的状态
privatevoidEnableControls()
//基于串口的打开与否,设置控件状态
gbPortSettings.Enabled=!
ComPort.IsOpen;
btns.Enabled=btnstop.Enabled=txtSendData.Enabled=btnSend.Enabled=ComPort.IsOpen;
if(ComPort.IsOpen)btnOpenPort.Text="关闭串口";
elsebtnOpenPort.Text="打开串口";
//初始化组件的数据,为串口提供相关参数
privatevoidInitializeControlValues()
cmbParity.Items.Clear();cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
cmbStopBits.Items.Clear();cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
cmbPortName.Items.Clear();
foreach(stringsinSerialPort.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();
cmbBaudRate.Text=cmbBaudRate.Items[0].ToString();
EnableControls();
//十六进制转换字节数组
privatebyte[]HexStringToByteArray(strings)
s=s.Replace("","");
byte[]buffer=newbyte[s.Length/2];
for(inti=0;ibuffer[i/2]=(byte)Convert.ToByte(s.Substring(i,2),16);returnbuffer;}//字节数组转换十六进制privatestringByteArrayToHexString(byte[]data){StringBuildersb=newStringBuilder(data.Length*3);foreach(bytebindata)sb.Append(Convert.ToString(b,16).PadLeft(2,'0').PadRight(3,''));returnsb.ToString().ToUpper();}//显示数据日志privatevoidLog(LogMsgTypemsgtype,stringmsg){rtfTerminal.Invoke(newEventHandler(delegate{rtfTerminal.SelectedText=string.Empty;rtfTerminal.SelectionFont=newFont(rtfTerminal.SelectionFont,FontStyle.Bold);rtfTerminal.SelectionColor=LogMsgTypeColor[(int)msgtype];rtfTerminal.AppendText(msg);rtfTerminal.ScrollToCaret();}));}//串口发送方式#regionLocalPropertiesprivateDataModeCurrentDataMode{get{if(rbHex.Checked)returnDataMode.Hex;elsereturnDataMode.Text;}set{if(value==DataMode.Text)rbText.Checked=true;elserbHex.Checked=true;}}#endregion//发送数据privatevoidSendData(){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();}//////-------------------------------------------------------------///publicfrm_Main(){InitializeComponent();}privatevoidForm1_Load(objectsender,EventArgse){InitializeControlValues();ComPort.DataReceived+=newSerialDataReceivedEventHandler(port_DataReceived);}//打开串口privatevoidbtnOpenPort_Click(objectsender,EventArgse){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),cmbPari
buffer[i/2]=(byte)Convert.ToByte(s.Substring(i,2),16);
returnbuffer;
//字节数组转换十六进制
privatestringByteArrayToHexString(byte[]data)
StringBuildersb=newStringBuilder(data.Length*3);
foreach(bytebindata)
sb.Append(Convert.ToString(b,16).PadLeft(2,'0').PadRight(3,''));
returnsb.ToString().ToUpper();
//显示数据日志
privatevoidLog(LogMsgTypemsgtype,stringmsg)
rtfTerminal.Invoke(newEventHandler(delegate
rtfTerminal.SelectedText=string.Empty;
rtfTerminal.SelectionFont=newFont(rtfTerminal.SelectionFont,FontStyle.Bold);
rtfTerminal.SelectionColor=LogMsgTypeColor[(int)msgtype];
rtfTerminal.AppendText(msg);
rtfTerminal.ScrollToCaret();
}));
//串口发送方式
#regionLocalProperties
privateDataModeCurrentDataMode
get
if(rbHex.Checked)returnDataMode.Hex;
elsereturnDataMode.Text;
set
if(value==DataMode.Text)rbText.Checked=true;
elserbHex.Checked=true;
//发送数据
privatevoidSendData()
if(CurrentDataMode==DataMode.Text)
//发送用户的文本到串口
ComPort.Write(txtSendData.Text);
//将用户的文本显示到数据窗口
Log(LogMsgType.Outgoing,txtSendData.Text+"\n");
else
//转换用户十六进制数据到字节数组
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();
///
///-------------------------------------------------------------
publicfrm_Main()
InitializeComponent();
privatevoidForm1_Load(objectsender,EventArgse)
InitializeControlValues();
ComPort.DataReceived+=newSerialDataReceivedEventHandler(port_DataReceived);
//打开串口
privatevoidbtnOpenPort_Click(objectsender,EventArgse)
if(ComPort.IsOpen)ComPort.Close();
//设置串口参数
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),cmbPari
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1