After reviewing your code, here are a few things that I think you might want to consider:
- Declare the serial port at the class level.
- Create, initialize, and open the serial port in the form load handler.
- Set the serial port properties based upon the modem manufacturer's recommendations, not on code copied from some other source.
- After writing to the serial port, wait the amount of time recommended by the modem manufacturer.
- Declare a handler for the DataReceived event. Unless you specifically inhibit modem success messages, you will be able to see your application's interactions with the modem.
- Declare a handler for the ErrorReceived event. Here you will be able to determine what went wrong.
Keeping those items in mind, here is a rework of your code:
using System;
using System.IO.Ports;
using System.Threading;
using System.Windows.Forms;
namespace CallApp
{
public partial class Form1 : Form
{
SerialPort serial_port = null;
protected override void OnFormClosed ( FormClosedEventArgs e )
{
base.OnFormClosed ( e );
if ( serial_port != null )
{
if ( serial_port.IsOpen )
{
serial_port.Close ( );
}
serial_port.Dispose ( );
serial_port = null;
}
}
private void Form1_Load ( object sender,
EventArgs e )
{
serial_port = new SerialPort ( );
serial_port.DataReceived +=
new SerialDataReceivedEventHandler (
serial_port_DataReceived );
serial_port.ErrorReceived +=
new SerialErrorReceivedEventHandler (
serial_port_ErrorReceived );
serial_port.PortName = "COM3";
serial_port.BaudRate = 9600;
serial_port.Parity = Parity.None;
serial_port.DataBits = 8;
serial_port.StopBits = StopBits.One;
serial_port.Handshake = Handshake.XOnXOff;
serial_port.DtrEnable = true;
serial_port.RtsEnable = true;
serial_port.NewLine = Environment.NewLine;
try
{
serial_port.Open ( );
}
catch ( Exception ex )
{
throw new ApplicationException (
"Failed to open serial port" +
ex.Message + ex.StackTrace );
}
}
public Form1 ( )
{
InitializeComponent ( );
}
private void button1_Click ( object sender,
EventArgs e )
{
try
{
if ( !serial_port.IsOpen )
{
MessageBox.Show ( "Serial port is not opened",
"Serial Port Error" );
return;
}
serial_port.WriteLine ( "AT" );
Thread.Sleep ( 1000 );
serial_port.WriteLine ( "ATD=\"" +
"7600684319;" +
"\"" );
Thread.Sleep ( 1000 );
}
catch ( Exception ex )
{
MessageBox.Show ( ex.Message + ex.StackTrace );
}
}
private void serial_port_DataReceived (
object sender,
SerialDataReceivedEventArgs e )
{
string received_string = String.Empty;
SerialPort serial_port = ( SerialPort ) sender;
received_string = serial_port.ReadExisting ( );
MessageBox.Show ( received_string,
"Recieved" );
}
void serial_port_ErrorReceived (
object sender,
SerialErrorReceivedEventArgs e )
{
SerialPort serial_port = ( SerialPort ) sender;
MessageBox.Show ( "Serial Port error",
"Error" );
}
}
}
Even without a modem on COM3, the following log is displayed:
AT
OK
ATD="7600684319;"
NO DIALTONE
Hope that helps.