visual basic 6.0 comm端口代码错误

时间:2013-01-09 16:23:19

标签: vb6 serial-port client-server

我实际上是在尝试从port1获取数据,但会生成错误Invalid port number

代码是:

Private Sub Command1_Click()
    MsgBox ("The port is open " & MSComm1.PortOpen)
    If (MSComm1.PortOpen = False) Then
    MSComm1.PortOpen = True
    End If
    Command1.Enabled = False
    Command2.Enabled = True
End Sub

Private Sub Command2_Click()
    If (MSComm1.PortOpen = True) Then
    MSComm1.PortOpen = False
    End If
    Command1.Enabled = True
    Command2.Enabled = False
End Sub

Private Sub Form_Load()
    With MSComm1
    .CommPort = 1
    .RThreshold = 1
    .RTSEnable = True
    .Settings = "9600,N,8,1"
    .InputLen = 127
    .SThreshold = 1
    End With
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If (MSComm1.PortOpen = True) Then
    MSComm1.PortOpen = False
    End If
End Sub

Private Sub MSComm1_OnComm()
    Dim Buffer As String

    Select Case MSComm1.CommEvent
    Case comEvReceive
    'Text1.Text = " "
    Buffer = MSComm1.Input
    Text1.Text = Text1.Text & Buffer
    End Select
End Sub

2 个答案:

答案 0 :(得分:1)

尝试不同的COM端口。 1到16之间的数字是可以接受的。

' Open the serial port
MSComm1.CommPort = 2
MSComm1.Settings = "9600,N,8,1"
MSComm1.PortOpen = True

“CommPort属性设置要打开的串口。假设调制解调器连接到COM2,上面的示例将值设置为2(COM2)并连接到调制解调器。您可以设置CommPort属性值到1到16之间的任何数字(默认值为1)。但是,如果将此值设置为运行应用程序的系统不存在的COM端口,则会生成错误。“

酱:dx.eng.uiowa.edu/eedesign/MScomm.doc

答案 1 :(得分:0)

查看我在以下答案中发布的代码:

search for available com ports

运行该代码将为您提供可用的COM端口列表

在代码中使用它,让代码从该列表中选择一个com端口