public partial class Form1 : Form
{
SerialPort sp;
public Form1()
{
InitializeComponent();
sp = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
MessageBox.Show("Initiate Form1");
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Form Load");
s();
MessageBox.Show("register DataReceive Event");
}
public void s()
{
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private void button1_Click(object sender, EventArgs e)//打开端口
{
//打开端口
try
{
if (sp.IsOpen)
{
MessageBox.Show("port is open!");
sp.Close();
sp.Open();
MessageBox.Show("port is open!");
}
else
{
MessageBox.Show("port is closed,then open it!");
sp.Open();
MessageBox.Show("port is open!");
}
}
catch(Exception ex)
{
ex.Message.ToString();
}
}
private void button2_Click(object sender, EventArgs e) //send AT 指令
{
MessageBox.Show("in 2");
if (sp.IsOpen)
{
//发送指令
sp.WriteLine("AT\n");
MessageBox.Show("send a command!");
}
else
{
MessageBox.Show("please open the Port,first!");
}
MessageBox.Show("out 2");
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//this.Invoke(new EventHandler(Add_Received));
MessageBox.Show("in event");
}
private void button5_Click(object sender, EventArgs e)
{
sp.Close();
this.Close();
}
}
发送了“AT”这个指令,就没反应了