VB6是否可以通过串口发送类型(结构)的全部内容? 以下示例无效。
Private Type CommFrameStruct
node As String
Inputs As Byte
Outputs As Byte
End Type
表单加载...
Dim msg As CommFrameStruct
msg.node = "TEST"
msg.Inputs = 5
msg.Outputs = 2
MSComm1.PortOpen = True
MSComm1.Output = msg
答案 0 :(得分:2)
您必须将MSComm控件的InputMode属性设置为comInputModeBinary
然后,您可以将UDT转换为raay of bytes并发送
两个快速示例项目:
发送UDT的一个项目:
' form with :
' 1 command button: name=Command1
' 1 MSComm control: name=MSComm1
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Type CommFrameStruct
node As String * 10
Inputs As Byte
Outputs As Byte
End Type
Private Sub Command1_Click()
Dim msg As CommFrameStruct
Dim bytArr() As Byte
msg.node = "TEST"
msg.Inputs = 5
msg.Outputs = 2
ReDim bytArr(Len(msg) - 1) As Byte
CopyMemory bytArr(0), msg, Len(msg)
MSComm1.Output = bytArr
End Sub
Private Sub Form_Load()
With MSComm1
.InputMode = comInputModeBinary
.Settings = "115200,N,8,1"
.PortOpen = True
End With 'MSCOmm1
End Sub
一个接收UDT的项目:
'1 form with :
' 1 Textbox control: name=Text1 multiline=true
' 1 MSComm control : name=MSComm1
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Type CommFrameStruct
node As String * 10
Inputs As Byte
Outputs As Byte
End Type
Private mudtMsg As CommFrameStruct
Private Sub Form_Load()
With MSComm1
.InputMode = comInputModeBinary
.RThreshold = Len(mudtMsg)
.Settings = "115200,N,8,1"
.PortOpen = True
End With 'MSComm1
End Sub
Private Sub Form_Resize()
Text1.Move 0, 0, ScaleWidth, ScaleHeight
End Sub
Private Sub MSComm1_OnComm()
Dim lngIndex As Long
Dim bytArr() As Byte
With MSComm1
Select Case .CommEvent
Case comEvReceive
bytArr = .Input
For lngIndex = 0 To UBound(bytArr)
ShowText "Byte " & CStr(lngIndex) & " : " & CStr(bytArr(lngIndex))
Next lngIndex
CopyMemory mudtMsg, bytArr(0), Len(mudtMsg)
ShowText "Node: " & mudtMsg.node
ShowText "Inputs: " & mudtMsg.Inputs
ShowText "Outputs: " & mudtMsg.Outputs
End Select
End With 'MSComm1
End Sub
Private Sub ShowText(strText As String)
Text1.SelText = vbCrLf & strText
End Sub
可能有更优雅的方式(特别是将UDT转换为字节数组并返回),但这似乎有效:)