private void MyInitializeComponent()
{
string[] ports = MulGetHardwareInfo(HardwareEnum.Win32_PnPEntity, "Name");
foreach (string port in ports)
{
// show the instance
string Temp;
/*将名称修改为COMn:Name的形式*/
int indexStart, indexEnd, lengthCOM;
indexStart = port.IndexOf("COM");
indexEnd = port.Length;
lengthCOM = indexEnd - indexStart;
Temp = port.Substring(indexStart, lengthCOM);
Temp = Temp.Insert(lengthCOM, port.Substring(0, indexStart));
Temp = Temp.Replace(')', ':');
Temp = Temp.Replace('(', ' ');
this.comboBoxSelectCOM.Items.Add(Temp);
}
comboBoxSelectCOM.SelectedIndex = 0;
comboBoxBaudRate.SelectedIndex = Properties.Settings.Default.BaudRateIndex;
comboBoxDataBit.SelectedIndex = Properties.Settings.Default.DataBitsIndex;
comboBoxStopBit.SelectedIndex = Properties.Settings.Default.StopBitsIndex;
comboBoxParity.SelectedIndex = Properties.Settings.Default.ParityIndex;
isHexForShow = Properties.Settings.Default.CheckedHexForRecv;
isHexForSend = Properties.Settings.Default.CheckedHexForSend;
checkBoxHexForRecv.Checked = isHexForShow;
checkBoxHexForSend.Checked = isHexForSend;
checkBoxShowThem.Checked = Properties.Settings.Default.CheckedShowThem;
if (checkBoxShowThem.Checked)
{
textBoxRecvData.BackColor = Color.White;
textBoxRecvData.ForeColor = Color.Black;
}
else
{
textBoxRecvData.BackColor = Color.Black;
textBoxRecvData.ForeColor = Color.Lime;
}
isTimeStamp = Properties.Settings.Default.CheckedTimeStamp;
checkBoxTimeStamp.Checked = isTimeStamp;
toolStripStatusLabelTime.Text = DateTime.Now.ToString();
bytesHadRecv = 0;
bytesHadSend = 0;
isSendRdy = true;
_serialPort = new SerialPort();
myCOMSReSet();
_serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.recvDataFromCOM);//数据接收
RecvQueue = new Queue<Byte>(_serialPort.ReadBufferSize);
keepThreaHandle = true;
threadHandleData = new Thread(handleData); //数据处理
threadSendData = new Thread(sendData);
threadHandleData.Start();
threadSendData.Start();
}
/*事件驱动接收串口数据并保存到缓冲队列中*/
private void recvDataFromCOM(object sender, SerialDataReceivedEventArgs e)
{
int i, BytesToRead;
BytesToRead = _serialPort.BytesToRead;
Byte[] ByteBuff = new Byte[BytesToRead];
_serialPort.Read(ByteBuff, 0, BytesToRead);
for (i = 0; i < BytesToRead; i++)
{
RecvQueue.Enqueue(ByteBuff[i]);
}
}
|