VB将输入文本框的数字分割并按十六进制发送

◆首先文本输入区域添加如下代码,实现将输入文本按回车符分割,并提前有效数字。

Private Sub Text2_KeyPress(KeyAscii AsInteger)

‘注意选择文本文档事件的类型

Dim tmp() As String

Dim aa As String * 1

Dim rd As String

Dim i As Integer

Dim reload As Integer

Dim response

 

aa = Chr$(KeyAscii)

If aa = Chr(13) And pc_draw_flag = TrueThen

   tmp = Split(Text2.Text, Chr(13)) '把目标数组按分隔符chr(13)分割

   For i = 0 To UBound(tmp)    'UBound()取数组内元素的个数

   rd = getnum(CStr(tmp(i)))

   Next i

    route(route_num) = "&H"& Hex(rd)‘提示,此处处理较为重要

   route_num = route_num + 1

   Text8.Text = route_num

   If route_num = 10 Then

       response = MsgBox("路径存储已达上限!是否重新规划?", vbYesNo + vbDefaultButton2 + vbInformation, "提示信息!")

       If response = vbYes Then

           route_num = 0

       Else

           MsgBox "路径存储已完成,请点击发送按钮!", vbOKOnly + vbInformation, "提示信息!"

       End If

   End If 

End If

 

End Sub

其中用到了getnum过程,其代码如下,起到提取数字并进行连接的作用。

Function getnum(sp As String) As String

Dim vi As String

For i = 1 To Len(sp)

   vi = Mid(sp, i)

   If IsNumeric(vi) Then

       getnum = getnum & vi

       Exit For

   End If

   Next

End Function

◆MSComm1初始化时注意将参数,若设置不正确,则接受会出现问题,其他参数正常设置即可。

MSComm1.InputMode= comInputModeBinary

'重要突破点,VB参考:串口控件的inputmode属性确定input属性读取的数据类型,如果设置inputmode为cominputmodetext,input属性通过一个variant返回文本数据,如果设置inputmode为cominputmodebinary,input属性通过一个variant返回二进制数据的数组,此时方可进行二进制转换。

◆然后在MSComm1的事件处理中,做如下处理,注意划线语句,

Select Case MSComm1.CommEvent

 Case 2

 buffer = MSComm1.Input

 staylonglowpower = staylonglowpower + 1

  Fori = 0 To UBound(buffer)

   If Len(Hex(buffer(i))) = 1 Then

    rec_data = rec_data & "0"& Hex(buffer(i)) & " "

   Else

   rec_data = rec_data & Hex(buffer(i)) & " "

   End If

 Next i

  EndSelect

显示如下写即可

Text1.Text =Text1.Text + rec_data + " "

当然在txt控件的change事件里做如下处理使其支持动态显示或者说光标总是位于最前位置。

Text1.SelStart =Len(Text1)

◆发送部分如下写

Private SubCmdSend_Click()

 

IfMSComm1.PortOpen = True Then

   

    If pc_draw_flag = True And OptSendHex.Value= True Then

        MSComm1.Output = route‘定义的一个0-9十个byte的数组

        send_num = send_num + 10

        Text7.Text = send_num

    End If

   

    If Text2.Text = "" Orpc_draw_flag = False Then

        MsgBox "发送数据不能为空,请进行路径规划或输入字符!", vbOKOnly + vbInformation, "提示信息!"

    Else

        If OptSendHex.Value = True Then

            MSComm1.InputMode =comInputModeBinary

            MSComm1.InputLen = 0

        Else

            MSComm1.InputMode =comInputModeText

            MSComm1.InputLen = 1

        End If

'        MSComm1.Output = Trim(Val(Text2.Text))

    End If

Else

    MsgBox "串口没有打开,请打开串口!",vbOKOnly + vbInformation, "提示信息!"

End If

 

route_num = 0

If pc_draw_flag= True And MSComm1.PortOpen = True And Text2.Text <> "" Then

 

For i = 0 To 9

Text2.Text =Text2.Text & route(i) & " "

If i = 9 Then

    Text2.Text = Text2.Text & Chr(13) &Chr(10)

End If

Next i

End If


原文地址:https://www.cnblogs.com/siahekai/p/11000834.html