我在尝试打开串行端口时遇到问题,但实际情况是:
当我告诉系统打开端口时,Try函数不会捕捉到任何错误但当我问串行端口是否打开时,它说它不是
我正在使用带有.NET 3.9 Compact框架的Visual Studio 2015来调试WCE2013
try
{
string porta = "COM2";
new frmcomunic().serialPort1.PortName = porta;
new frmcomunic().serialPort1.BaudRate = 38400;
new frmcomunic().serialPort1.DataBits = 8;
new frmcomunic().serialPort1.Parity = System.IO.Ports.Parity.Even;
new frmcomunic().serialPort1.StopBits = System.IO.Ports.StopBits.One;
new frmcomunic().serialPort1.Handshake = System.IO.Ports.Handshake.XOnXOff;
new frmcomunic().serialPort1.ReadTimeout = 500;
new frmcomunic().serialPort1.WriteTimeout = 500;
new frmcomunic().serialPort1.Open();
new frmcomunic().ProgressBar1.Value = 100;
new frmcomunic().btcl.Enabled = true;
new frmcomunic().cbport.Enabled = false;
new frmcomunic().cbrate.Enabled = false;
new frmcomunic().btop.Enabled = false;
new frmcomunic().btcl.Enabled = true;
new frmcomunic().cbport.Enabled = true;
new frmcomunic().cbrate.Enabled = true;
new frmcomunic().ler = true;
}
catch (Exception err)
{
MessageBox.Show("Erro de Comunicação", "Aviso", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
if (new frmcomunic().serialPort1.IsOpen)
MessageBox.Show("Porta aberta", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
else MessageBox.Show("ERRO", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
这对我来说是
public SerialPort GetSerialPort(bool open)
{
SerialPort Port = new SerialPort();
Port.PortName = PortName;
Port.BaudRate = BaudRate;
Port.DataBits = DataBits;
Port.Parity = Parity;
Port.StopBits = StopBits;
Port.Handshake = Handshake;
Port.ReadTimeout = ReadTimeout;
Port.WriteTimeout = WriteTimeout;
if (open)
Port.Open();
return Port;
}