0

Em vez de eu ter que colocar manualmente a porta no campo txt, como fazer ela ser auto-detectar e preencher o campo ?

    private void btnSend_Click(object sender, EventArgs e)
    {
        try
        {
           SerialPort sp = new SerialPort();
            sp.PortName = txtPort.Text;
            sp.Open();
            sp.WriteLine("AT" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine("AT+CMGF=1" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine("AT+CSCS=\"GSM\"" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine("AT+CMGS=\"" + txtPhoneNumber.Text + "\"" + Environment.NewLine);
            Thread.Sleep(100);
            sp.WriteLine(txtMessage.Text + Environment.NewLine);
            Thread.Sleep(100);
            sp.Write(new byte[] { 26 }, 0, 1);
            Thread.Sleep(100);
            var response = sp.ReadExisting();
            if (response.Contains("ERRO"))
                MessageBox.Show("Envio falhou , tente novamente daqui 5 segundos !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                MessageBox.Show("SMS Enviado !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
            sp.Close();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

}

1
  • O objeto SerialPort tem métodos e propriedades que podem te ajudar a encontrar a COM correta. Como a propriedade PortName sem argumentos que retorna as portas disponíveis. Abra cada uma, mande alguns comandos AT de inicialização e veja se o retorno foi o correto do dispositivo serial. msdn.microsoft.com/pt-br/library/…
    – user1084
    24/04/2017 às 0:45

1 Resposta 1

0

Insira dentro de um botao_click

    Try
        With SerialPort1
            'aqui pega nome da porta COM (COM11)
            .PortName = Label3.Text '
            .BaudRate = 9600
            .Parity = IO.Ports.Parity.None
            .DataBits = 8
            .StopBits = IO.Ports.StopBits.One
            .Handshake = IO.Ports.Handshake.None
            .RtsEnable = True
            .ReceivedBytesThreshold = 1
            .NewLine = vbCr
            .ReadTimeout = 1000
            .Open()

        End With
        If SerialPort1.IsOpen Then
            Thread.Sleep(1000)
            Label4.Text = "CONECTADO COM SUCESSO !"
        Else
            Label4.Text = "Conexao do modem Falhou !"
            Label4.ForeColor = Color.Red
        End If
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .