GSM Modem俗称“短信猫”,PC可通过串口与其通信,通过向其所连接的串口发送AT指令控制我们的“猫”发送短信
写这样一个软件,首先要了解串口通信,.NET已经为我们封装了SerialPort类,方便串口通信。为了熟悉此串口类,我简单实现了一个串口调试器。
运行效果:
主要源代码:
using System;
using System.Drawing;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace 串口调试器
{
public partial class Form1 : Form
{
//hotkeyWinapi声明:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
SerialPort sp = new SerialPort(); //声明串口类
bool stoptb2 = false;
//发送字节计数
int fscout = 0;
//接收字节计数
int jscout = 0;
//十六进制显示标志
bool ishex = false;
//委托
delegate void HandleInterfaceUpdateDelegate(string text); //委托,此为重点
HandleInterfaceUpdateDelegate interfaceUpdateHandle = null;
public Form1()
{
InitializeComponent();
}
//重载函数
protected override void WndProc(ref Message m)
{
//
const int WM_HOTKEY = 0x0312;
if (m.Msg == WM_HOTKEY)
{
int id = m.WParam.ToInt32();
//Ctrl+Z
Byte[] byte1 = new Byte[1];
byte1[0] = 0x1A;
if (id == 100)
{
if (sp.IsOpen == true)
{
sp.Write(byte1, 0, 1);
}
}
}
base.WndProc(ref m);
}
private void Form1_Load(object sender, EventArgs e)
{
//初始化状态栏
toolStripStatusLabel1.Text = "串口调试器正在初始化 ";
//热键注册Ctrl+Alt+Z
RegisterHotKey(this.Handle, 100, 6, Convert.ToUInt32(Keys.Z));
//初始化combox1
foreach (string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
//初始化combox2
comboBox2.Items.Add("300");
comboBox2.Items.Add("600");
comboBox2.Items.Add("1200");
comboBox2.Items.Add("2400");
comboBox2.Items.Add("4800");
comboBox2.Items.Add("9600");
comboBox2.Items.Add("19200");
comboBox2.Items.Add("38400");
comboBox2.Items.Add("76800");
comboBox2.Items.Add("115200");
comboBox2.SelectedIndex = 5;
//初始化combox3
comboBox3.Items.Add("None");
comboBox3.Items.Add("Odd");
comboBox3.Items.Add("Even");
comboBox3.SelectedIndex = 0;
//初始化combox4
comboBox4.Items.Add("8");
comboBox4.Items.Add("7");
comboBox4.Items.Add("6");
comboBox4.SelectedIndex = 0;
//初始化combox5
comboBox5.Items.Add("1");
comboBox5.Items.Add("2");
comboBox5.SelectedIndex = 0;
//textbox1初始化
textBox1.Text = "1000";
//有串口
if (comboBox1.Items.Count > 0)
{
comboBox1.SelectedIndex = 0;
//串口变量初始化
sp.PortName = comboBox1.SelectedItem.ToString();
sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
sp.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
sp.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
sp.RtsEnable = true;
sp.ReceivedBytesThreshold = 1;//设置 DataReceived 事件发生前内部输入缓冲区中的字节数
sp.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.sp_DataReceived); //DataReceived事件委托
}
else
{
label9.Text = "未检测到串口";
label9.ForeColor = Color.Red;
}
//委托实例化
interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox); //实例化委托对象
//初始化状态栏
toolStripStatusLabel1.Text = "串口调试器初始化成功 ";
}
//委托的函数
private void UpdateTextBox(string text)
{
if (stoptb2 == false)
{
textBox3.Text += text;
}
//更新接收显示
toolStripStatusLabel3.Text = String.Format(" 接收:{0} 字节 ", jscout);
}
//DataReceived事件委托方法
private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int readlen = sp.BytesToRead;
//接收计数
jscout += readlen;
byte[] readBuffer = new byte[sp.ReadBufferSize];
sp.Read(readBuffer, 0, readBuffer.Length);
if (ishex)
{
string readbuf = null;
//十六进制格式化数据
for(int i=0;i<readlen;i++)
{
string s = String.Format("{0:X}", Convert.ToInt32(readBuffer[i]));
if (s.Length > 1)
{
readbuf += s+" ";
}
else
{
readbuf += "0" + s + " ";
}
}
this.Invoke(interfaceUpdateHandle, readbuf);
}
else
{
this.Invoke(interfaceUpdateHandle, new string[] { Encoding.UTF8.GetString(readBuffer) });
}
}
private void button1_Click(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
try
{
sp.Open();
//清空缓冲区
sp.DiscardInBuffer();
sp.DiscardOutBuffer();
}
catch (Exception)
{
label9.Text = "串口无法连接";
return;
}
button1.Text = "断开串口";
label6.Text = "已连接";
label6.ForeColor = Color.Green;
label9.Text = sp.PortName + "," + sp.BaudRate + "," + sp.Parity + "," + sp.DataBits + "," + sp.StopBits;
//改变状态栏
toolStripStatusLabel1.Text = " " + label9.Text + " ";
}
else
{
if (checkBox2.Checked)
{
MessageBox.Show("正在发送,请先停止自动发送");
return;
}
sp.Close();
label6.Text = "已断开";
label6.ForeColor = Color.Red;
label9.Text = " 串口关闭状态";
button1.Text = "连接串口";
//改变状态栏
toolStripStatusLabel1.Text = "串口关闭状态 不能操作串口";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (stoptb2 == false) //停止显示标志置位
{
stoptb2 = true;
button2.Text = "继续显示";
}
else
{
stoptb2 = false; //停止显示标志复位
button2.Text = "停止显示";
}
}
private void button3_Click(object sender, EventArgs e)
{
textBox3.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
if (sp.IsOpen == true)
{
fscout += textBox2.Text.Length;
sp.Write(textBox2.Text);
toolStripStatusLabel2.Text = String.Format(" 发送:{0} 字节 ", fscout);
}
else
{
MessageBox.Show("串口未打开");
}
}
private void button5_Click(object sender, EventArgs e)
{
fscout = 0;
toolStripStatusLabel2.Text = " 发送:0 字节 ";
}
private void button6_Click(object sender, EventArgs e)
{
jscout = 0;
toolStripStatusLabel3.Text = " 接收:0 字节 ";
}
private void button7_Click(object sender, EventArgs e)
{
About abFrm = new About();
abFrm.Owner = this;
abFrm.ShowDialog();
}
//程序退出
private void button8_Click(object sender, EventArgs e)
{
UnregisterHotKey(this.Handle, 100);
sp.Close();
this.Close();
}
//combox1改变
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
sp.PortName = comboBox1.SelectedItem.ToString();
}
}
//combox2改变
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
sp.BaudRate = Convert.ToInt32(comboBox2.SelectedItem.ToString());
}
//combox3改变
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
sp.Parity = (Parity)Enum.Parse(typeof(Parity), comboBox3.SelectedItem.ToString());
}
//combox4改变
private void comboBox4_SelectedIndexChanged(object sender, EventArgs e)
{
sp.DataBits = int.Parse(comboBox4.SelectedItem.ToString());
}
//combox5改变
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), comboBox5.SelectedItem.ToString());
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
ishex = true;
}
else
{
ishex = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sp.IsOpen == true)
{
fscout += textBox2.Text.Length;
sp.Write(textBox2.Text);
toolStripStatusLabel2.Text = String.Format(" 发送:{0} 字节 ", fscout);
}
else
{
MessageBox.Show("串口未打开");
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
checkBox2.Checked = false;
}
else
{
timer1.Enabled = checkBox2.Checked;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == null||textBox1.Text=="")
{
timer1.Interval = 1000;
}
else
{
timer1.Interval = Convert.ToInt32(textBox1.Text);
}
}
private void checkBox2_Click(object sender, EventArgs e)
{
if (sp.IsOpen == false)
{
MessageBox.Show("串口未连接");
}
}
}
}
作为C#新手的我第一次完成一个比较完整的程序
不足之处欢迎大家拍砖
附件:工程项目文件