VB控制COM口短信收发
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VB控制COM口短信收发相关的知识,希望对你有一定的参考价值。
设备可以使用标准的AT指令,我需要一个VB写的短信收发,只要简单的可以进行收发就行,我主要是学习.
之前提问过,但因为留下了邮箱总被百度删,几百分就这么浪费掉了.有嘛就用百度HI联系.
设备是3618手机,一切正常,本身不需要任何驱动就可以正常工作.
我是要学习,我也不需要现成的程序,我就是想看到代码,然后自己根据简单的收发来开发出更强大的工具.
Dim SendSuccessCount As Integer
Dim SendFailedCount As Integer
Dim ReceiveCount As Integer
Dim WorkFlag As Boolean
Dim ReceiveData As String
Dim SendSuccess As Integer '-1等待;0失败;1成功
Dim ReceiveSuccess As Integer '-1等待;0失败;1成功
Private Sub Command1_Click()
RequestRecMsg MsgIndex.Text
End Sub
Private Sub Form_Load()
SmsInit 3, "9600,n,8,1"
End Sub
Private Function SmsInit(Port As Integer, setstr As String) As Boolean
SmsInit = False
If SmsOpen(Port, setstr) = False Then Exit Function
WorkFlag = True
SendSuccessCount = 0
SendFailedCount = 0
ReceiveCount = 0
ReceiveData = ""
SendSuccess = 0
ReceiveSuccess = 0
SmsInit = True
End Function
Private Function SmsSend(MoblieID As String, TxtMessage As String) As Boolean '被timer1_timer调用
Dim TxtMsg As String
SmsSend = False
If WorkFlag = False Or SendSuccess = -1 Then Exit Function
'编码
TxtMsg = Encode(TxtMessage)
If MSComm1.PortOpen Then
MSComm1.Output = "AT+CMGS=" + Chr(34) + MoblieID + Chr(34) + Chr(13) '送出短信目的号码
MSComm1.Output = TxtMsg + Chr(26) '送出已编码后的短信内容
SendSuccess = -1
SmsSend = True
End If
End Function
Function SmsOpen(Port As Integer, Setings As String) As Integer '被opensms_click 调用
On Error GoTo ErrHandle
SmsOpen = False
If MSComm1.PortOpen Then MSComm1.PortOpen = False
MSComm1.CommPort = Port
MSComm1.Settings = Setings
MSComm1.PortOpen = True
If MSComm1.PortOpen Then
SmsOpen = True
MSComm1.Output = "ATE0" + Chr(13) + Chr(10)
MSComm1.RThreshold = 1
MSComm1.Output = "AT+CMGF=1" + Chr(13) + Chr(10)
MSComm1.Output = "AT+CSMP=4,167,0,8" + Chr(13) + Chr(10)
'上边两行语句作为联机是初始化用的命令
End If
Exit Function
ErrHandle:
MsgBox "错误: " + Str(Err.Number) + Chr(13) + Chr(10) + Err.Description, _
vbOKOnly + vbCritical, App.Title
End Function
Private Sub MSComm1_OnComm()
Dim buffer As String
Dim i As Integer, j As Integer
Dim NextFlag As Boolean
ReceiveData = ReceiveData + MSComm1.Input
Do
NextFlag = False
j = InStr(ReceiveData, "+CMS")
If j > 0 Then
ReceiveSuccess = 0
End If
i = InStr(ReceiveData, "+CMGR:")
j = InStr(ReceiveData, "+CMGS")
If j = 0 And i = 0 And Len(ReceiveData) > 8 Then '删除接收区中无用的数据
ReceiveData = Mid(ReceiveData, Len(ReceiveData) - 7)
End If
If j > 0 And j < i And 14 >= Len(ReceiveData) - j Then '最前的数据为发送返回结果
If SendSuccess = -1 Then
buffer = Mid(ReceiveData, j, 14)
If InStr(buffer, "OK") > 0 Then
SendSuccess = 1
SendSuccessCount = SendSuccessCount + 1
Else
SendSuccess = 0
SendFailedCount = SendFailedCount + 1
End If
End If
ReceiveData = Mid(ReceiveData, j + 14)
NextFlag = True
Else
If i > 0 Then
j = InStr(ReceiveData, Chr(13) + Chr(10) + "OK")
If j > 0 Then
buffer = Mid(ReceiveData, i, j - i)
ReceiveSuccess = 0
If Analyze(buffer) Then
ReceiveSuccess = 1 '接收成功
ReceiveCount = ReceiveCount + 1
End If
ReceiveData = Mid(ReceiveData, j + 3)
NextFlag = True
End If
End If
End If
Loop While NextFlag
End Sub
Function Analyze(RecMsg As String) As Boolean
Dim tel As String, msg As String, time As String
Analyze = AnalyzeRecMsg(buffer, tel, msg, time)
If Analyze = True Then
'用户处理
MobileTel.Text = tel
SendMsg.Text = msg
' Label1.Caption = time
End If
End Function
Private Sub Send_Click()
Success = -1
If Len(MobileTel.Text) < 11 Or Len(MobileTel.Text) > 12 Then
MsgBox "请输入正确的手机号"
Exit Sub
End If
If Len(SendMsg.Text) < 1 Or Len(SendMsg.Text) > 80 Then
MsgBox "必须信息或输入的信息不能超过80"
Exit Sub
End If
Status.Panels(2).Text = "正发送..."
SmsSend MobileTel.Text, SendMsg.Text
End Sub
Private Function Encode(TxtMessage As String) As String
Dim High As String, Low As String, OneWord As String
Dim i As Integer
For i = 1 To Len(TxtMessage) '将短信息转化为编码
OneWord = Mid(TxtMessage, i, 1)
Low = Hex(AscB(MidB(OneWord, 1, 1)))
High = Hex(AscB(MidB(OneWord, 2, 1)))
If Len(High) = 1 Then High = "0" + High
If Len(Low) = 1 Then Low = "0" + Low
Encode = Encode + High + Low '得到的编码
Next i
End Function
Private Function Decode(EncodeMessage As String) As String
Dim Word(2) As Byte
Dim ascii As String
Dim Temp As String
Dim j As Integer, Pos As Integer
Pos = 1
j = 1
Do
If j >= Len(EncodeMessage) Then
Exit Function
End If
ascii = Mid(EncodeMessage, j, 2)
j = j + 2
Word(Pos) = Val("&H" + ascii)
Pos = Pos - 1
If Pos < 0 Then
Temp = Word
Decode = Decode + Left(Temp, 1)
Pos = 1
End If
Loop
End Function
Private Function GetBPNumber(RecDecodeMsg As String) As String
Dim i As Integer
Dim Start As Boolean
Dim OneWord As String
GetBPNumber = ""
Start = False
For i = 1 To Len(RecDecodeMsg)
OneWord = Mid(RecDecodeMsg, i, 1)
If OneWord >= "0" And OneWord <= "9" Then
Start = True
GetBPNumber = GetBPNumber + OneWord
Else
If Start = False Then
If OneWord <> " " Then Exit Function
Else
If OneWord = " " Then
Do
i = i + 1
OneWord = Mid(RecDecodeMsg, i, 1)
Loop While OneWord = " " And i < Len(RecDecodeMsg)
End If
RecDecodeMsg = Mid(RecDecodeMsg, i)
Exit Function
End If
End If
Next i
End Function
Private Function AnalyzeRecMsg(ByVal RecMsg As String, ByRef MobileNumber As String, ByRef msg As String, ByRef MsgTime As String) As Boolean
Dim i As Integer, j As Integer
Dim AnalyzeMsg As String
Dim Length As Integer
AnalyzeRecMsg = False
i = InStr(RecMsg, "+CMGR:")
If i < 1 Then Exit Function
AnalyzeMsg = Mid(RecMsg, i + 6)
i = InStr(AnalyzeMsg, Chr(34) + "+86")
If i < 1 Then Exit Function
j = InStr(i + 1, AnalyzeMsg, Chr(34))
If j < i Then Exit Function
MobileNumber = Mid(AnalyzeMsg, i + 4, j - i - 4)
AnalyzeMsg = Mid(AnalyzeMsg, j)
i = InStr(AnalyzeMsg, ",")
If i < 1 Then Exit Function
i = InStr(i, AnalyzeMsg, ",")
If i < 1 Then Exit Function
i = InStr(i, AnalyzeMsg, Chr(34))
If i < 1 Then Exit Function
j = InStr(i + 1, AnalyzeMsg, Chr(34))
If j < i Then Exit Function
MsgTime = Mid(AnalyzeMsg, i + 1, j - i - 4)
AnalyzeMsg = Mid(AnalyzeMsg, j)
i = InStr(AnalyzeMsg, Chr(13) + Chr(10))
If i < 1 Then Exit Function
j = InStrRev(AnalyzeMsg, ",", i)
If j < 1 Then Exit Function
Length = Val(Mid(AnalyzeMsg, j + 1, i - j - 1))
j = InStr(i + 2, AnalyzeMsg, Chr(13) + Chr(10))
If j < 1 Then Exit Function
msg = Mid(AnalyzeMsg, i + 2, j - i - 2)
If Len(msg) > Length Then
msg = Decode(msg)
End If
AnalyzeRecMsg = True
End Function
Private Function RequestRecMsg(MsgIndex As String) As Boolean
RequestRecMsg = False
If ReceiveSuccess = -1 Then Exit Function
ReceiveSuccess = -1
RequestRecMsg = True
MSComm1.Output = "AT+CSDH=1" + Chr(13) + Chr(10)
MSComm1.Output = "AT+CMGR=" + MsgIndex + Chr(13) + Chr(10)
End Function
Private Function RequestDelMsg(MsgIndex As String)
MSComm1.Output = "AT+CMGD=" + MsgIndex + Chr(13) + Chr(10)
End Function
参考技术A 百度有字数限制,连源代码的一个类都粘不上,下面这个类是发送接收短信的类的一部分,这个类总共有一千二百多行,根本粘不全,你可以参考一下。短信终端操作的关键是短信的编码和解码,英文资料很多,中文的基本找不到,你可以多查些资料。
Option Explicit On
Public Class Jwc
'_______________声明mscomm控件__________________
Public MSComm1 As New MSCommLib.MSComm
'__________________串口调试_____________________
Dim bug As String
Public B_bug As Boolean = False
'__________________串口设置_____________________
Public L_com(256) As String
Public I_P As Integer = 1 '端口号
Public S_Set As String = "9600,n,8,1" '初始字符串
Public C_open As Boolean = False
Public ret_l As Double
'__________________短信共用变量_________________
Dim l_msg_c As Integer = 0
Dim l_msg_i As Integer = 0
Dim l_msg_t As Integer = 0
Dim l_msg_x As Integer = 16
'__________________读取短信_____________________
Public ID1 As String '短信编号
Public ID2 As String '短信分类
Public n1 As Integer '短信中心号码长度
Public n2 As Integer '被叫号码长度
Public n3 As Integer '用户数据长度
Public n4 As Integer '日期长度
Public np1 As String '短信中心号码
Public np2 As String '被叫号码
Public da1 As String '日期
Public sp1 As String '用户数据
Public Cont As Integer '短信个数
Public scod As String '编码方式
Dim ms(1000, 10)
'_______________发送短信________________________
Public s_mg As String
Public m_succ As Boolean '短信发送状态
Public cs1 As String = "0891"
Public cs2 As String = "11000D91"
Public cs3 As String = "000800"
Public Lms As Integer
'_______________接收短信________________________
Public mg_count As Integer = 0
Public mg_ade(1000) As Integer
Public mg_N As Boolean = False
'_______________读取联系人______________________
Dim Pbook(1000, 2) As String
Public bookcont As Integer
'_______________打开设备________________________
Public Function PhoOpen() As Boolean
Dim i As Integer
Dim j As Integer
Dim n As Integer
Dim coms(256) As Integer
PhoOpen = False
If C_open Then
PhoOpen = True
Exit Function
End If
For i = 0 To 255
L_com(i) = ""
Next
j = 0
For i = 1 To 64
If CheckCom(i) Then
L_com(j) = i
'MsgBox(j & " " & i)
j = j + 1
End If
Next i
'触发OnComm事件的字符长度
For i = 0 To j - 1
n = L_com(i)
'MsgBox(i & " " & n)
I_P = n '记录当前端口号
If CheckModem(n) Then
'MsgBox("连接成功!")
PhoOpen = True
C_open = True
PhoLoading()
Exit For
End If
Next i
End Function
'_______________发送AT指令______________________
Public Function ATcode(ByVal s As String) As String
If Not C_open Then
Call PhoOpen()
If Not C_open Then
'MsgBox("未发现设备!", vbInformation)
ATcode = "未发现设备!"
Exit Function
End If
End If
ATcode = ""
MSComm1.Output = s
Dim i As Integer
Dim t As String
Dim Sall As String = ""
For i = 0 To 1000
System.Threading.Thread.Sleep(10)
t = MSComm1.Input
While Len(t) > 0
Sall = Sall & t
t = ""
i = 0
End While
If ATend(Sall) Then
Exit For
End If
If i >= 1000 Then
Me.C_open = False
PhoClose()
End If
Next
ret_l = Len(Sall)
'If ret_l = 0 Then
' Sall = "连接超时!"
'End If
CheckNewMsg(Sall)
ATcode = Sall
End Function
Public Function ATend(ByVal s As String) As Boolean
Dim i As Integer
Dim t As String = ""
Dim Sall As String = ""
For i = 1 To Len(s)
t = Mid(s, i, 1)
If t <> Chr(13) And t <> Chr(10) And t <> Chr(32) Then
Sall = Sall + t
End If
Next
ATend = False
m_succ = False
If Right(Sall, 1) = ">" Then
ATend = True
m_succ = True
Exit Function
End If
If Right(Sall, 2) = "OK" Then
ATend = True
m_succ = True
Exit Function
End If
If Right(Sall, 5) = "ERROR" Then
ATend = True
Exit Function
End If
If Right(Sall, 7) = "CARRIER" Then
ATend = True
Exit Function
End If
End Function
'_______________读取短信________________________
Function Getmsg(ByVal i As Integer, ByVal j As Integer) As String
Getmsg = ""
Try
Getmsg = ms(i, j)
Catch ex As Exception
End Try
End Function
'_____________发送短信_________________________
Function SMG(ByVal n1 As String, ByVal n2 As String, ByVal s1 As String) As Boolean
Dim l1 As String
Dim l2 As String
Dim l3 As String '十六进制长度
Dim ln1 As String
Dim ln2 As String
Dim ln3 As String '十进制长度
Dim t1, t2, t3 As String
Dim mg As String
Dim m(255) As String
Dim m_l(255) As String
Dim m_c As Integer
Dim ms1, ms2 As String
Dim i As Integer = 0
t1 = ""
t2 = ""
t3 = ""
ms1 = ""
ms2 = ""
'_________处理短信中心号码__________
t1 = Trim(n1)
If Left(t1, 1) = "+" Then '去掉号码前面的+号
t1 = Right(t1, Len(t1) - 1)
End If
ln1 = Len(t1)
If ln1 < 16 Then
l1 = "0" & Hex(Len(t1)) '获得短信中心号码长度
Else
l1 = Hex(Len(t1))
End If
t1 = NtoS(n1) '翻转短信中心号码
'MsgBox(l1)
'__________处理联系人号码___________
t2 = Trim(n2)
If Len(t2) = 11 Then '当号码为11位时补足13位
t2 = "86" & t2 '前面加86
End If
ln2 = Len(t2)
If ln2 < 16 Then
l2 = "0" & Hex(Len(t2)) '获得联系人号码长度
Else
l2 = Hex(Len(t2))
End If
'MsgBox(l2)
t2 = NtoS(t2) '翻转联系人号码
If l2 = "0D" Then
cs2 = "1100" & l2 & "91"
Else
cs2 = "1100" & l2 & "81"
End If
'_________获得短信内容长度__________
s1 = Trim(s1) '去掉两边的空格
If CheckAsc(s1) Then '检查消息内容(汉字/字母)
ln3 = Len(s1) '字符串长度
Else
ln3 = Len(s1) * 2 '计算汉字长度(字节)
End If
If ln3 < 16 Then '将消息长度转为16进制,不足两位时前面补0
l3 = "0" & Hex(ln3)
Else
l3 = Hex(ln3)
End If
'_________短信内容编码转化__________
m_c = 0
l_msg_x = Rnd() * 240 + 15 '长短信标识
While l_msg_x < 16 Or l_msg_x > 255
l_msg_x = Rnd() * 240 + 15
End While
If CheckAsc(s1) Then '判断消息类型(汉字/字母)
cs3 = "000022" '后两位为有效期22*5分钟
If Len(s1) > 160 Then
m_c = Len(s1) / 150
If Len(s1) > m_c * 150 <> 0 Then
m_c = m_c + 1
End If
Else
'普通英文短信编码
t3 = Ttoc7(s1) 'Bit-7编码
End If
'长短信编码
For i = 1 To m_c
m(i) = Mid(s1, (i - 1) * 150 + 1, 150)
m(i) = Ttoc7(m(i))
If m_c < 16 Then
ms1 = "0" & Hex(m_c)
Else
ms1 = Hex(m_c)
End If
If i < 16 Then
ms2 = "0" & Hex(i)
Else
ms2 = Hex(i)
End If
m(i) = "050003" & Hex(l_msg_x) & ms1 & ms2 & m(i)
m_l(i) = Hex(Len(m(i)) / 2)
Next
Else
cs3 = "000822"
If Len(s1) > 70 Then
m_c = Len(s1) / 60
If Len(s1) > m_c * 60 Then
m_c = m_c + 1
End If
Else
t3 = StoU(s1) 'unicode编码
End If
For i = 1 To m_c
m(i) = Mid(s1, (i - 1) * 60 + 1, 60)
m(i) = StoU(m(i))
If m_c < 16 Then
ms1 = "0" & Hex(m_c)
Else
ms1 = Hex(m_c)
End If
If i < 16 Then
ms2 = "0" & Hex(i)
Else
ms2 = Hex(i)
End If
m(i) = "050003" & Hex(l_msg_x) & ms1 & ms2 & m(i)
m_l(i) = Hex(Len(m(i)) / 2)
Next
End If
'___________要发送的数据____________
If m_c = 0 Then
'发送普通短信
mg = cs2 & t2 & cs3 & l3 & t3
Lms = Len(mg) / 2
If Len(Trim(n2)) = 11 And n1 <> "00" Then
mg = cs1 & t1 & mg
Else
mg = "00" & mg
End If
'___________数据发送方式____________
Dbug(ATcode("at" & vbCr))
Dbug(ATcode("at+csq" & vbCr))
Dbug(ATcode("AT+CMGF=0" & vbCr))
'____________发送数据_______________
Dbug(ATcode("AT+CMGS=" & Str(Lms) + vbCr))
Dbug(ATcode(mg & Chr(26)))
'___________获得发送结果____________
Else
'发送长短信
For i = 1 To m_c
l3 = m_l(i)
t3 = m(i)
mg = cs2 & t2 & cs3 & l3 & t3
Lms = Len(mg) / 2
If Len(Trim(n2)) = 11 And n1 <> "00" Then
mg = cs1 & t1 & mg
Else
mg = "00" & mg
End If
'___________数据发送方式____________
Dbug(ATcode("at" & vbCr))
Dbug(ATcode("at+csq" & vbCr))
Dbug(ATcode("AT+CMGF=0" & vbCr))
'____________发送数据_______________
Dbug(ATcode("AT+CMGS=" & Str(Lms) + vbCr))
Dbug(ATcode(mg & Chr(26)))
'___________获得发送结果____________
Next
End If
SMG = m_succ
End Function
……
……
End Class本回答被提问者采纳 参考技术B 我也想学学。
Android收发短信
效果:点击发送短信开始发送短信
收到短信时将短信的内容显示出来
代码如下:
一、权限声明
<uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" />
二、代码实现
我们的短信功能用到了SmsManager和SmsMessage两个主要类。
当收不到短信时候,手动在应用管理中将应用的短信收发权限打开
//Java /** * Created by Linda on 16/5/14. * 短信的收发 * 根绝国际标准 每条短信的长度不超过160 个字符 * 如果短信长度过长,可以调用sendMultipartTextMessage()分隔成多条短信来发送 */ public class MesaageActivity extends Activity { private TextView sender; private TextView content; private EditText to;//接收短信的手机号码 private EditText msgInput;//发送信息的内容 private Button send; private IntentFilter receiveFilter;//短信接收 private MessageReceiver messageReceiver; private IntentFilter sendFilter;//短信发送 private SendStatusReceiver sendStatusReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.message); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); to = (EditText) findViewById(R.id.to); msgInput = (EditText) findViewById(R.id.msg_input); send = (Button) findViewById(R.id.send); // 注册短信接收的广播 receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); receiveFilter.setPriority(100); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); // 注册监听短信发送的广播 sendFilter = new IntentFilter(); sendFilter.addAction("SENT_SMS_ACTION"); sendStatusReceiver = new SendStatusReceiver(); registerReceiver(sendStatusReceiver, sendFilter); // 点击按钮发送短信 send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SmsManager smsManager = SmsManager.getDefault(); Intent sentIntent = new Intent("SENT_SMS_ACTION"); PendingIntent pi = PendingIntent.getBroadcast( MesaageActivity.this, 0, sentIntent, 0); //根据号码和内容发送短信(需要权限) smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null); } }); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageReceiver); unregisterReceiver(sendStatusReceiver); } //短信接收的广播 class MessageReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus");//获取短信数组 SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);//将pdu字符数组转换成SmsMessage对象 } String address = messages[0].getOriginatingAddress();//获取短信发送方的号码 String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody();//获取短信的内容 } sender.setText(address); content.setText(fullMessage); abortBroadcast(); } } //监听广播是否发送成功的广播 class SendStatusReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (getResultCode() == RESULT_OK) { Toast.makeText(context, "Send succeeded", Toast.LENGTH_LONG) .show(); } else { Toast.makeText(context, "Send failed", Toast.LENGTH_LONG) .show(); } } } }
以上是关于VB控制COM口短信收发的主要内容,如果未能解决你的问题,请参考以下文章