这是 Robert Grier 的回答(Visual Basic Programmer's Guide to Serial Communications, 第 4 版 ISBN 1-890422-28-2的作者)我非常感谢他的帮助,因此与所有感兴趣的人分享。
将开关的一侧连接到 DTR 输出(连接器的针脚 4),将开关的另一侧连接到 DCD 输入(针脚 1)
从您的窗体的工具箱中删除 Comm 控件并添加一个标签。在代码中:
Private Sub Form_Load()
On Error Resume Next
With MSComm1
.CommPort = 3 'use the actual port number that is created when you install your USB adapter
.PortOpen = True
.DTREnable = True
If .PortOpen = False Then MsgBox "Unable to open serial port."
End With
End Sub
Private Sub MSComm1_OnComm()
With MSComm1
If .CDHolding = True Then
Label1.Caption = "Switch On"
Label1.BackColor = vbGreen
Else
Label1.Caption = "Switch Off"
Label1.BackColor = vbRed
End If
End With
End Sub