怎样在vb中自动检测到可用串口号的具体程序代码

怎样在vb中自动检测到可用串口号的具体程序代码
2024-12-02 11:29:11
推荐回答(5个)
回答1:

  j = 0
  For i = 1 To 16 Step 1
  If comISP.PortOpen = True Then '先关闭串口
  comISP.PortOpen = False
  End If

  comISP.CommPort = i
  On Error Resume Next '说明当一个运行时错误发生时,控件转到紧接着发生错误的语句之后的语句,并在此继续运行。访问对象时要使用这种形式而不使用 On Error GoTo。
  comISP.PortOpen = True
  If Err.Number <> 8002 Then '无效的串口号。这样可以检测到虚拟串口,如果用Err.Number = 0的话检测不到虚拟串口
  If j = 0 Then
  j = i
  End If
  cboPort.AddItem "COM" & i '生成串口选择列表
  End If
  comISP.PortOpen = False
  Next i

  If j >= 1 Then
  cboPort.Text = "COM" & j '自动打开可用的最小串口号
  comISP.CommPort = j
  comISP.PortOpen = True
  cmdOpenCom.Caption = "关闭串口"
  shpCOM.FillColor = vbGreen
  If Err.Number = 8005 Then '串口已打开,vbExclamation '
  comISP.PortOpen = False
  cboPort.Text = ""
  cmdOpenCom.Caption = "打开串口"
  shpCOM.FillColor = vbRed
  End If
  End If

回答2:

试着写了几行代码,运行后正确的列出了3个串口!

  form上放2个控件:mscomm一个,combo一个。

  代码如下:

Private Sub Form_Load()
On Error GoTo Handle_Error
For i = 1 To 16
MSComm1.CommPort = i
MSComm1.PortOpen = True
'If Err.Number = comPortInvalid Then
' Print "Error"
'Else
Combo1.AddItem "COM" & i
'End If
MSComm1.PortOpen = False
Next i
Handle_Error: Print "Error"
End Sub

回答3:

直接给你代码不一定能调试成功,跟你说说思路,就是用com控件挨个端口去试。

回答4:

vb.net的话
For Each sp As String In My.Computer.Ports.SerialPortNames
cbxport.Items.Add(sp)
Next

vb6.0的话要调用API查看串口相关信息存在的注册表。
HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM

通过读注册表的方法获得串口数量,当然也可以获得串口号了。
Option Explicit
Private Declare Function RegOpenKey Lib "advapi32.dll " Alias "RegOpenKeyA " (ByVal hKey As Long, ByVal lpSubKey As String, phkResult As Long) As Long
Private Declare Function RegQueryInfoKey Lib "advapi32.dll " Alias "RegQueryInfoKeyA " (ByVal hKey As Long, ByVal lpClass As String, lpcbClass As Long, ByVal lpReserved As Long, lpcSubKeys As Long, lpcbMaxSubKeyLen As Long, lpcbMaxClassLen As Long, lpcValues As Long, lpcbMaxValueNameLen As Long, lpcbMaxValueLen As Long, lpcbSecurityDescriptor As Long, lpftLastWriteTime As Long) As Long

Private Const HKEY_LOCAL_MACHINE = &H80000002

' 获得当前系统的 COM 口的数量
Function GetCOMCount() As Integer
Dim ret As Long, cntCOM As Long
RegOpenKey HKEY_LOCAL_MACHINE, "HARDWARE\DEVICEMAP\SERIALCOMM ", ret
RegQueryInfoKey ret, " ", 0, 0, 0, 0, 0, cntCOM, 0, 0, 0, 0
GetCOMCount = cntCOM
End Function

Private Sub Command1_Click()
MsgBox "您的机器有 " & GetCOMCount & " 个串口。 ", vbOKOnly, "串口数量 "
End Sub

回答5:

上面的回答是个好办法,也是个简单办法。
如果不是这样,那么就读注册表吧,那里什么都有