(求助)串口 winform 调用目标发生异常
sp.DataBits = Form2.DataBits;
sp.PortName = Form2.PortName;
if (Form2.StopBits == "1 ")
{
sp.StopBits = StopBits.One;
}
if (Form2.StopBits == "1.5 ")
{
sp.StopBits = StopBits.OnePointFive;
}
if (Form2.StopBits == "2 ")
{
sp.StopBits = StopBits.Two;
}
int[] BaudRate = new int[6];
BaudRate[0] = 4800;
BaudRate[1] = 9600;
BaudRate[2] = 38400;
BaudRate[3] = 57600;
BaudRate[4] = 19200;
BaudRate[5] = 115200;
for (int i = 0; i < 6; i++)
{
sp.BaudRate = BaudRate[i];
for (int n = 0; n < 3; n++)
{
if (n == 0)
{
sp.Parity = Parity.None;
}
if (n == 1)
{
sp.Parity = Parity.Even;
}
if (n == 2)
{
sp.Parity = Parity.Odd;
}
try
{
sp.Open();
toolStripButton1.Text = "串口关闭 ";
sp.Write( "@#R00000000 < ");
char[] buffer = new char[9];
Thread.Sleep(1000);
sp.Read(buffer, 0, buffer.Length);
if (buffer[0] == 'W ')
{
string xs = sp.PortName + ", " + BaudRate[i].ToString() + ", " + sp.Parity.ToString() + ", " + sp.DataBits + ", " + sp.StopBits;
toolStripStatusLabel3.Text = xs;
MessageBox.Show( "检测到电台 ");
qd = buffer;
return;
}
}
catch
{
sp.Close();
}
}
}
MessageBox.Show( "未检测到电台 ");----在这里出现 "调用目标发生异常 "的信息
toolStripButton1.Text = "串口打开 ";
return;
}
这个问题相当怪,有时出错,有时不会的
[解决办法]
你在catch上加Exception参数,然后看ex.Message可能对你有帮助,至少能知道是执行那一步时出错,时好时坏很可能与你的串口设备有关
[解决办法]
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
sp.Close();
}