0

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);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
  • 2
    What's with all these `new`s? – 500 - Internal Server Error Jul 30 '18 at 12:02
  • You create a new object with every call to `new`. Just create 1 object and use that: `var frm = new frmcomunic(); frm.serialPort1.PortName = porta; frm.serialPort1.BaudRate = 38400; .....` – 001 Jul 30 '18 at 12:05
  • 4
    The problem is related to lack of programming language knowledge. Please read manual about [objects creation](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/objects). – Renatas M. Jul 30 '18 at 12:11

1 Answers1

0

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