/********************** serial data receive event *****************************/ Private voidSerialport_datareceived (Objectsender, Serialdatareceivedeventargs e) {utf8encoding utf8encoding=Newutf8encoding (); byte[] Readbytes =New byte[ This. Serialport.bytestoread]; intnum = This. Serialport.read (Readbytes,0, readbytes.length); This. Builder. Clear ();//Empty Cache This. Received_count + = (Long) Num;//Plus receive Count This. Rxtextbox.invoke ((EventHandler)Delegate { if(! This. rxcharsetup.checked)//determine the format of the received data{//Get character length for(inti =0; i < readbytes.length; i++) { byteb = Readbytes[i];//Display hexadecimal This. Builder. Append ("0x"+ b.tostring ("X2") +" "); } } Else { //Display character formatting This. Builder. Append (Encoding.GetEncoding ("GB2312"). GetString (readbytes)); } This. Rxtextbox.selectionstart = This. Rxtextbox.textlength; This. Rxtextbox.appendtext ( This. Builder. ToString ()); This. Rxnumdata. Text ="Rx"+ This. Received_count. ToString (); //Update Send Count }); }
/********************** send button *****************************/ Private voidSenddata_click (Objectsender, EventArgs e) { if(! This. Serialport.isopen) {MessageBox.Show ("serial port is not open!!! ","Warning"); } Else { intnum; if( This. txdatasetup.checked) {MatchCollection MatchCollection= Regex.Matches ( This. Txtextbox.text,"(? i) [\\da-f]{2}"); List<byte> list =Newlist<byte>(); foreach(Match matchinchmatchcollection) {list. ADD (byte. Parse (match. Value, Numberstyles.hexnumber)); } This. Serialport.write (list. ToArray (),0, List. Count); Num=list. Count; } Else { This. Serialport.writeline ( This. Txtextbox.text); Num= This. TxtextBox.Text.Length +2; } This. Send_count + = (Long) num; This. Txnumdata. Text ="Tx"+ This. Send_count. ToString (); //Update Receive Count } }
C # serial port send receive data