第1个回答 2011-07-07
试着写了几行代码,运行后正确的列出了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个回答 2011-07-12
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