當前位置:名人名言大全網 - 短信平臺 - 怎麽用VB6.0編寫手機短信發送

怎麽用VB6.0編寫手機短信發送

因為手機短消息的發送是以PDU串的形式發送出去的,中文字符以Unicode碼來表示,所以在發送中文短消息之前必須首先將中文字符轉換為Unicode碼,下面的函數

將實現這個功能。這個函數主要應用到VB自帶的壹個格式轉換函數:ChrW()將中文轉換為Unicode碼。

Public Function chg(rmsg As String) As String

Dim tep As String

Dim temp As String

Dim i As Integer

Dim b As Integer

tep = rmsg

i = Len(tep)

b = i / 4

If i = b * 4 Then

b = b - 1

tep = Left(tep, b * 4)

Else

tep = Left(tep, b * 4)

End If

chg = ""

For i = 1 To b

temp = "&H" & Mid(tep, (i - 1) * 4 + 1, 4)

chg = chg & ChrW(CInt(Val(temp)))

Next i

End Function

同上,為了發送以PDU模式發送短消息,必須將手機號碼和對方手機號碼也轉換為PDU格式,下面的函數就是為了實現這種轉換:

Public Function telc(num As String) As String

Dim tl As Integer

Dim ltem, rtem, ttem As String

Dim ti As Integer

ttem = ""

tl = Len(num)

If tl <> 11 And tl <> 13 Then

MsgBox "wrong number." & tl

Exit Function

End If

If tl = 11 Then

tl = tl + 2

num = "86" & num

End If

For ti = 1 To tl Step 2

ltem = Mid(num, ti, 1)

rtem = Mid(num, ti + 1, 1)

If ti = tl Then rtem = "F"

ttem = ttem & rtem & ltem

Next ti

telc = ttem

End 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 _Boolean

Dim pdu, psmsc, pnum, pmsg As String

Dim leng As String

Dim length As Integer

length = Len(msg)

length = 2 * length

leng = Hex(length)

If length < 16 Then leng = "0" & leng

psmsc = Trim(telc(csca))

pnum = Trim(telc(num))

pmsg = Trim(ascg(msg))

pdu = prex & psmsc & midx & pnum & sufx & leng & pmsg

sleep(1)

mobcomm.Output = "AT+CMGF=0" + vbCr

mobcomm.Output = "AT+CMGS=" & Str(15 + length) + vbCr

mobcomm.Output = pdu & Chr$(26)

sleep(1)

Sendsms = True

End Function

因為手機同壹時間只能處理壹件事情,因此這個函數只負責發送短信,關於短信發送成功與否以及閱讀短信的部分集中在壹起處理。判斷手機短信發送成功與

否主要由AT+CMGS命令執行以後的返回碼來決定(可參見前文的AT指令介紹部分)。

為了防止手機因過於繁忙而出錯,這裏采取了壹定的方法讓手機有充分的時間處理發送和接收及刪除等操作。Sleep()函數正是為此而設計的,在發送及刪除操

作後都會讓程序暫停壹秒,這樣就不至於使得手機過於繁忙。

Unicode碼解碼函數

相比於手機短信的發送而言,手機短信的接收主要的工作正好與之相反。手機短信的發送需要將待發送的短信內容轉換為Unicode碼,而短信的接收則需要將接

收到的Unicode碼轉換成中文字符。下面的函數將實現解碼功能。同手機短信發送的編碼函數壹樣,這裏也應用了壹個VB內置的函數AscW()函數來將Unicode碼轉

換為中文:

Public Function ascg(smsg As String) As String

Dim si, sb As Integer

Dim stmp As Integer

Dim stemp As String

sb = Len(smsg)

ascg = ""

For si = 1 To sb

stmp = AscW(Mid(smsg, si, 1))

If Abs(stmp) < 127 Then

stemp = "00" & Hex(stmp)

Else

stemp = Hex(stmp)

End If

ascg = ascg & stemp

Next si

ascg = Trim(ascg)

End Function

2 手機短信接收函數

相對於短信的發送函數而言,短信的接收相當簡單,只需要以下的三行代碼就完成了。但是它使用的技術卻決不比短信的發送少,這裏主要用到了Mscomm控件

的Output屬性和AT+CMGR指令。

Public Sub readsms(rnum As String)

mobcomm.Output = "AT+CMGF=1" + vbCr

mobcomm.Output = "AT+CMGR=" & rnum + vbCr

End Sub

謝謝啊~~