因为手机短消息的发送是以PDU串的形式发送出去的,中文字符以Unicode码来表示,所以在发送中文短消息之前必须首先将中文字符转换为Unicode码,下面的函数将实现这个功能。这个函数主要应用到VB自带的一个格式转换函数:ChrW()将中文转换为Unicode码。
Public Function chg(rmsg As String) As StringDim tep As StringDim temp As StringDim i As IntegerDim b As Integertep = rmsgi = Len(tep)b = i / 4If i = b * 4 Thenb = b - 1tep = Left(tep, b * 4)Elsetep = Left(tep, b * 4)End Ifchg = ""For i = 1 To btemp = "&H" & Mid(tep, (i - 1) * 4 + 1, 4)chg = chg & ChrW(CInt(Val(temp)))Next iEnd Function 短信中心手机号码的PDU串转换函数同上,为了发送以PDU模式发送短消息,必须将手机号码和对方手机号码也转换为PDU格式,下面的函数就是为了实现这种转换:Public Function telc(num As String) As StringDim tl As IntegerDim ltem, rtem, ttem As StringDim ti As Integerttem = ""tl = Len(num)If tl <> 11 And tl <> 13 ThenMsgBox "wrong number." & tlExit FunctionEnd IfIf tl = 11 Thentl = tl + 2num = "86" & numEnd IfFor ti = 1 To tl Step 2ltem = Mid(num, ti, 1)rtem = Mid(num, ti + 1, 1)If ti = tl Then rtem = "F"ttem = ttem & rtem & ltemNext titelc = ttemEnd Function 手机号码有两种表示方法:11位和13位(带国家码86),一般手机发送时都是以13位形式表示的,所以以上的函数还有一个功能是自动将11位格式手机号码转换为13位形式,然后再转换为PDU串。手机短信的发送手机短信的发送主要借助于VB的Mscomm控件实现,关于Mscomm控件,前面的技术介绍部分有详细介绍。短信的发送是由AT+CMGS指令完成的,采用PDU模式发送,函数代码如下:Const prex = "0891"Const midx = "11000D91"Const sufx = "000800"Public Function Sendsms(csca As String, num As String, msg As String) As _BooleanDim pdu, psmsc, pnum, pmsg As StringDim leng As StringDim length As Integerlength = Len(msg)length = 2 * lengthleng = Hex(length)If length < 16 Then leng = "0" & lengpsmsc = Trim(telc(csca))pnum = Trim(telc(num))pmsg = Trim(ascg(msg))pdu = prex & psmsc & midx & pnum & sufx & leng & pmsgsleep(1)mobcomm.Output = "AT+CMGF=0" + vbCrmobcomm.Output = "AT+CMGS=" & Str(15 + length) + vbCrmobcomm.Output = pdu & Chr$(26)sleep(1)Sendsms = TrueEnd Function 因为手机同一时间只能处理一件事情,因此这个函数只负责发送短信,关于短信发送成功与否以及阅读短信的部分集中在一起处理。判断手机短信发送成功与否主要由AT+CMGS命令执行以后的返回码来决定(可参见前文的AT指令介绍部分)。为了防止手机因过于繁忙而出错,这里采取了一定的方法让手机有充分的时间处理发送和接收及删除等操作。Sleep()函数正是为此而设计的,在发送及删除操作后都会让程序暂停一秒,这样就不至于使得手机过于繁忙。手机短信的接收Unicode码解码函数相比于手机短信的发送而言,手机短信的接收主要的工作正好与之相反。手机短信的发送需要将待发送的短信内容转换为Unicode码,而短信的接收则需要将接收到的Unicode码转换成中文字符。下面的函数将实现解码功能。同手机短信发送的编码函数一样,这里也应用了一个VB内置的函数AscW()函数来将Unicode码转换为中文:Public Function ascg(smsg As String) As StringDim si, sb As IntegerDim stmp As IntegerDim stemp As Stringsb = Len(smsg)ascg = ""For si = 1 To sbstmp = AscW(Mid(smsg, si, 1))If Abs(stmp) < 127 Thenstemp = "00" & Hex(stmp)Elsestemp = Hex(stmp)End Ifascg = ascg & stempNext siascg = Trim(ascg)End Function 手机短信接收函数相对于短信的发送函数而言,短信的接收相当简单,只需要以下的三行代码就完成了。但是它使用的技术却决不比短信的发送少,这里主要用到了Mscomm控件的Output属性和AT+CMGR指令。Public Sub readsms(rnum As String)mobcomm.Output = "AT+CMGF=1" + vbCrmobcomm.Output = "AT+CMGR=" & rnum + vbCr转自bbs.sendsms.cn