搞了半天,终于搞定了。。。帖出来备忘。。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; byte[] bse; MSCommLib.MSCommClass axMSComm1 = new MSCommLib.MSCommClass(); private void button1_Click(object sender, EventArgs e) { string a = "00 A5 04 03 00 03 06 "; byte[] bTemp = strToToHexByte(a); axMSComm1.Output = bTemp; Thread.Sleep(1500); string r = ReadData(); bse = strToToHexByte(r); textBox1.Text = r; label1.Text = co.ToString(); } private void Form1_Load(object sender, EventArgs e) { axMSComm1.CommPort = 1; axMSComm1.Settings = "9600,N,8,1"; axMSComm1.InputLen =1000; axMSComm1.RThreshold = 1; axMSComm1.RTSEnable = true; axMSComm1.DTREnable = true; axMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeBinary; Open(); } /// <summary> /// 字符串转16进制字节数组 /// </summary> /// <param name="hexString"></param> /// <returns></returns> private static byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } private void Open() { axMSComm1.PortOpen = true; } private int co=0; /// <summary> /// 字节数组转16进制字符串 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public string byteToHexStr(byte[] bytes) { string returnStr = ""; if (bytes != null) { co = bytes.Length; for (int i = 0; i < bytes.Length; i++) { returnStr += bytes[i].ToString("X2"); returnStr += " "; } } return returnStr; } /// <summary> /// 字节数组转16进制字符串2 /// </summary> /// <param name="bytes"></param> /// <returns></returns> private string ToHexString(byte[] bytes) { char[] chars = new char[bytes.Length * 2]; co = bytes.Length; for (int i = 0; i < bytes.Length; i++) { int b = bytes[i]; chars[i * 2] = hexDigits[b >> 4]; chars[i * 2 + 1] = hexDigits[b & 0xF]; } return new string(chars); } public string ReadData() { string results = ""; object o = axMSComm1.Input; results = this.byteToHexStr((byte[])o); return results; } private void button2_Click(object sender, EventArgs e) { textBox1.Text = string.Empty; label1.Text="0"; } private void button3_Click(object sender, EventArgs e) { string k = "00 A5 04 05 00 01 06 "; byte[] stemp = strToToHexByte(k); axMSComm1.Output = stemp; axMSComm1.Output = bse; Thread.Sleep(1500); textBox2.Text = ReadData(); } } }