Not being able to Open a Serial Port

174 views Asked by At

I´m having a problem with trying to open a serial port, But what happens is this:

When I tell the system to open the port, the Try Function doesn´t catch any error But when i ask if the serial port is open, it says that it isn´t

I´m using Visual Studio 2015 With a .NET 3.9 Compact framework to debug a 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);
1

There are 1 answers

0
Tomáš Tomčík On

this work for me

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;
            }