日期:2014-05-18  浏览次数:20957 次

c#写的通过串口写AT指令发短信的程序,大家帮忙看看!
该程序发短信不是很稳定,有时发短信正确,有时又没反应,有时把AT指令一起发了! 不知道什么原因!
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO.Ports;

namespace MultiLangTest
{
  public partial class SerialPortTest : Form
  {
  private SerialPort sp;
  public SerialPortTest()
  {
  InitializeComponent();
  }



  private void button1_Click(object sender, EventArgs e)
  {
  Parity p = Parity.None;
  switch (comboBox5.Text.ToLower())
  {
  case "none":
  p = Parity.None;
  break;
  case "odd":
  p = Parity.Odd;
  break;
  case "even":
  p = Parity.Even;
  break;
  case "mark":
  p = Parity.Mark;
  break;
  case "space":
  p = Parity.Space;
  break;
  default:
  break;
  }
  StopBits sb = StopBits.None;
  switch (comboBox4.Text.ToLower())
  {
  case "1":
  sb = StopBits.One;
  break;
  case "1.5":
  sb = StopBits.OnePointFive;
  break;
  case "2":
  sb = StopBits.Two;
  break;
  default:
  break;
  }

  sp = new SerialPort(comboBox1.Text, Convert.ToInt32(comboBox2.Text),
  p, Convert.ToInt32(comboBox3.Text), sb);

  //sp.DataReceived += new SerialDataReceivedEventHandler(this.ReadSMSData);

  if (sp.IsOpen)
  {
  //MessageBox.Show(string.Format("{0} 串口已经打开", comboBox1.Text));
  sp.Close();
  sp.Open();
  }
  try
  {
  sp.Open();
  }
  catch (UnauthorizedAccessException ex)
  {
  MessageBox.Show("错误:" + ex.Message);
  return;
  }
  }
  private void button2_Click(object sender, EventArgs e)
  {
   
  sp.Write("AT+CMGF=1\r"); 
  sp.Write("AT+CMGs=\"13316979816\"\r"); 
  sp.Write(this.textBox1.Text + "\x01a");//发送短信息,使用Ctrl+Z结束
  }

  private void groupBox1_Enter(object sender, EventArgs e)
  {

  }

  private void label8_Click(object sender, EventArgs e)
  {

  }

  private void textBox3_TextChanged(object sender, EventArgs e)
  {

  }

  priva