这是我的代码
public void ClosePort()
{
if (comPort.IsOpen == true)
{
//e.Cancel = true; //cancel the fom closing
Thread CloseDown = new Thread(new ThreadStart(CloseSerialOnExit)); //close port in new thread to avoid hang
//comPort.DiscardInBuffer();
//comPort.DiscardOutBuffer();
//comPort.Dispose();
CloseDown.Start(); //close port in new thread to avoid hang
DisplayData(MessageType.Error, "Port communication has been closed" + " " + DateTime.Now + "\n");
}
}
private void CloseSerialOnExit()
{
try
{
comPort.Dispose();
comPort.DiscardInBuffer();
comPort.DiscardOutBuffer();
comPort.Close(); //close the serial port
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //catch any serial port closing error messages
}
BeginInvoke(new EventHandler(NowClose)); //now close back in the main thread
}
private void NowClose(object sender, EventArgs e)
{
comPort.Dispose();
comPort.DiscardInBuffer();
comPort.DiscardOutBuffer();
comPort.Close(); //now close the form
}
public void BeginInvoke(Delegate method)
{
}
为什么串口没有关闭?当我点击[X]图标并退出程序时,在任务管理器中编程stil detect。 在正常情况下,上面的代码是有效的。但是当串口写入或读取数据代码不起作用,而不是关闭串口时,对这种情况有什么建议吗?感谢您的帮助和解决方案。
private void cmdClose_Click(object sender, EventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure to disconnect?", "WARNING",
MessageBoxButtons.OKCancel);
switch (result)
{
case DialogResult.OK:
{
comm.ClosePort();
cmdRefresh.Enabled = true;
cmdNewReport.Enabled = true;
cboPort.Enabled = true;
cboBaud.Enabled = true;
cboStop.Enabled = true;
cboParity.Enabled = true;
cboData.Enabled = true;
label9.Text = " ";
label11.Text = " ";
cmdOpen.Enabled = true;
//cmdSend.Enabled = true;
cmdClose.Enabled = false;
break;
}
case DialogResult.Cancel:
{
break;
}
}
}
上面的代码是我的按钮代码,它调用comPort.ClosePort();
void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//determine the mode the user selected (binary/string)
switch (CurrentTransmissionType)
{
//user chose string
case TransmissionType.Text:
//read data waiting in the buffer
string msg = comPort.ReadExisting();
//display the data to the user
DisplayData(MessageType.Incoming, msg + "\n");
break;
//user chose binary
case TransmissionType.Hex:
//retrieve number of bytes in the buffer
int OpeCode = 0;
int RequestID = 0;
int Product = 0;
int IPenNo = 0;
string status = " ";
while (true)
{
DateTime time = DateTime.Now; // Use current time.
string format = "dddddddd, MMMMM d, yyyy HH:mm:ss";
string currentTime = time.ToString(format);
byte[] TrueData = new byte[256];
try
{
int bytes = comPort.BytesToRead;
if (bytes == 0) continue;
//create a byte array to hold the awaiting data
byte[] comBuffer = new byte[bytes];
comPort.Read(comBuffer, 0, bytes);
DisplayData(MessageType.Incoming, "Hexa :" + ByteToHex(comBuffer) + "\n");
DisplayData(MessageType.Incoming, "Byte :" + bytes.ToString() + "\n");
if (bytes == 3)
{
var lines = File.ReadAllLines(Fullpath).ToList();
// Remove as many lines as you'd like from the end
if (lines.Count > 2)
{
lines.RemoveRange(lines.Count - 2, 2);
}
// Iterate backwards through the list until we've updated 2 (or more or less) lines
var linesUpdated = 0;
for (var i = lines.Count - 1; i >= 0 && linesUpdated < 1; i--)
{
if (lines[i].Contains("OK"))
{
lines[i] = lines[i].Replace("OK", "NG");
linesUpdated++;
}
}
File.WriteAllLines(Fullpath, lines.ToArray());
//DisplayData(MessageType.Incoming, "NG" + "\n");
}
if (bytes == 2)
{
continue;
}
int etx_ok = 0;
for (int i = 0; i < bytes; i++)
{
if (comBuffer[i] == 0x02)
{
//DisplayData(MessageType.Incoming, "cek II:" + checkStatus + "\n");
int length = comBuffer[i + 1];
DisplayData(MessageType.Incoming, "Length=" + length.ToString() + "\n");
if (String.IsNullOrEmpty(bytes.ToString()))
{
status = "NG";
}
if (length + i + 1 != bytes && status == " ")
{
DisplayData(MessageType.Incoming, length.ToString() + " " + i.ToString() + " " + bytes.ToString() + " ");
status = "NG";
DisplayData(MessageType.Incoming, "ERROR \n");
//break;
}
else
{
status = "OK";
}
DisplayData(MessageType.Incoming, "ini statusnya : " + status + "\n");
if (comBuffer[length + i - 1] == 0x03)
{
DisplayData(MessageType.Incoming, "ETX OK\n");
etx_ok = 1;
OpeCode = comBuffer[i + 2];
DisplayData(MessageType.Incoming, "OpeCode=" + OpeCode.ToString() + ",");
RequestID = comBuffer[i + 3];
DisplayData(MessageType.Incoming, "RequestID=" + RequestID.ToString() + ",");
int StoreCode = comBuffer[i + 4];
DisplayData(MessageType.Incoming, "StoreCode=" + StoreCode.ToString() + ",");
int ProductBatteryTraining = comBuffer[i + 5];
DisplayData(MessageType.Incoming, "ProductBatteryTraining=" + ProductBatteryTraining.ToString() + ",");
Product = ProductBatteryTraining >> 4;
DisplayData(MessageType.Incoming, " Product=" + Product.ToString() + ",");
int Battery = ProductBatteryTraining & 4;
DisplayData(MessageType.Incoming, " Batery=" + Battery.ToString() + ",");
int Training = ProductBatteryTraining & 1;
DisplayData(MessageType.Incoming, " Training=" + Training.ToString() + ",");
IPenNo = comBuffer[i + 6];
DisplayData(MessageType.Incoming, "IPenNo=" + IPenNo.ToString() + ",");
int CrcCalc = comBuffer[length + i] + 0x11;
for (int j = 7, k = 0; j < length; j++, k++)
{
//syswrite STDOUT , "TrueDataX " . $length . "\n";
DisplayData(MessageType.Incoming, "TrueDataX " + length.ToString() + "," + "\n");
TrueData[k] = comBuffer[i + j];
}
if (OpeCode == 0x63)
{
byte[] replyStr = new byte[] {
Convert.ToByte(0x45), Convert.ToByte(0x53), Convert.ToByte(0x4c), Convert.ToByte(0x14), Convert.ToByte(0x09), Convert.ToByte(0x00), //#Length Change
Convert.ToByte(0x02), Convert.ToByte(0x08),Convert.ToByte(OpeCode), Convert.ToByte(RequestID),Convert.ToByte(Product-1), Convert.ToByte(IPenNo), //#Reply Header Data
Convert.ToByte(0x00), //#Reply Status
Convert.ToByte(0x03), Convert.ToByte(CrcCalc), //#Footer Data
Convert.ToByte(0xcc), Convert.ToByte(0xcc)
};
comPort.Write(replyStr, 0, replyStr.Length);
//write file to textfile
//string path = @"d:\yosafat\testfile\tes1_Friday0916201614.33.txt";
string IPenID = IPenNo.ToString();
string appendText = ("IPen ID \t" + "Datetime\t\t\t\t\t" + "Status" + Environment.NewLine + IPenID + "\t\t" + currentTime + "\t\t" + status + Environment.NewLine);
File.AppendAllText(Fullpath, appendText);
}
}
else
{
OpeCode = 0;
//syswrite STDOUT , "ETX Bad Data" . $length . "\n";
DisplayData(MessageType.Incoming, "ETX Bad Data" + length.ToString() + "\n");
break;
}
}
if (etx_ok == 1)
{
break;
}
}
}
catch (Exception) { }
}
}
}