Code
主要代码如下:
定义委托
public delegate void ReceiveMessageHandle(string SendPhoneNumber, string SendTime, string SendContent);
/// <summary>
/// 接收信息事件
/// </summary>
public event ReceiveMessageHandle ReceiveMessageEvent;
formload事件中注册接收事件
s_port.DataReceived += new SerialDataReceivedEventHandle(s_port_DataReceived);
s_port.ReceivedBytesThreshold = 1;
//实例化自己定义的委托
ReceiveMessageEvent = new ReceiveMessageHandle(UpdateTextBox);//UpdateTextBox方法是将解码后的内容显示出来
接收事件
private void s_port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string response = string.Empty;
response = s_port.ReadExisting();
System.Threading.Thread.Sleep(200);
if (response.Length > 0 && response.IndexOf("+CMT:") != -1)
{
response = response.Replace("\r\n", "|");
int i = response.IndexOf("|");
if (i == 0)
i = 1;
else
i = 0;
i = response.IndexOf("|", i);
response = response.Remove(0, i);
response = response.Replace("|", "");
string SendPhoneNumber = string.Empty;
string SendContent = string.Empty;
DateTime SendTime = new DateTime();
PDUCoding.GSMCode code = new PDUCoding.GSMCode();
string SCA = "";
//将读出来的PDU串解码,读出来的是“+CMT:15950432221\r\nPDU串”,上面的代码是用remove方法将+CMT:15950432221\r\n去掉,response是发送人的号码加上发送时间加上发送内容的PDU串,下面进行解码,这些都没问题,能正确解码后显示出来
if (pduc.DecodingMsg(response, ref SendPhoneNumber, ref SendContent, ref SendTime, ref code, ref SCA))
{
if (ReceiveMessageEvent != null)
{
// 通知处理事件
this.BeginInvoke(ReceiveMessageEvent, new string[] { SendPhoneNumber.Trim(), SendTime.ToString().Trim(), SendContent.Trim() });
}
}
}
}
catch (Exception)
{
Close();
}
}
public void UpdateTextBox(string sendPhoneNumber, string sendTime, string sendContent)
{
txtMsg.AppendText("\r\n" + sendPhoneNumber);
txtMsg.AppendText("\r\n" + sendTime);
txtMsg.AppendText("\r\n" + sendContent);
}