作MCU项目时,经常用到串口UART通讯,把PC的RS232通过逻辑转换以后和MCU的UART相联。常会用VB、VC等编写一些小工具,VC偶学了很长的时候,但是没学会,没办法继续用丢人的VB。用vb编写串口通讯程序比较简单,使用控件MSCOM或者API都可以,使用COM以前会枚举PC上所有的COM,物理COM和虚拟的COM。对于windows XP系统串口映射在注册表 HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM里面,如图1。
图1 注册表中的SERIALCOM项
枚举所有的串口只需要读取注册表的这个子项就可一个了。可以调用读取Register的API完成。下面几个函数可能被用到。
RegCloseKey
RegEnumValue
RegOpenKeyEx
RegOpenKey
RegQueryValue
RegQueryValueEx
实例,新建图二所示的form
图2 COM口枚举实例
添加如下代码:
Option Explicit
Private Declare Function RegCloseKey Lib _
"advapi32.dll" (ByVal hKey As Long) As Long
Private Declare Function RegEnumValue Lib _
"advapi32.dll" Alias "RegEnumValueA" _
(ByVal hKey As Long, _
ByVal dwIndex As Long, _
ByVal lpValueName As String, _
lpcbValueName As Long, _
ByVal lpReserved As Long, _
lpType As Long, _
lpData As Byte, _
lpcbData As Long) As Long
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" _
(ByVal hKey As Long, _
ByVal lpSubKey As String, _
ByVal ulOptions As Long, _
ByVal samDesired As Long, _
phkResult As Long) As Long
Private Declare Function RegOpenKey Lib "advapi32.dll" Alias "RegOpenKeyA" _
(ByVal hKey As Long, _
ByVal lpSubKey As String, _
phkResult As Long) As Long
Const HKEY_LOCAL_MACHINE = &H80000002
Const REG_SZ = 1
Private Declare Function RegQueryValue Lib "advapi32.dll" Alias "RegQueryValueA" _
(ByVal hKey As Long, _
ByVal lpSubKey As String, _
ByVal lpValue As String, _
lpcbValue As Long) As Long
Private Declare Function RegQueryValueEx Lib "advapi32.dll" Alias "RegQueryValueExA" _
(ByVal hKey As Long, _
ByVal lpValueName As String, _
ByVal lpReserved As Long, _
lpType As Long, _
lpData As Any, _
lpcbData As Long) As Long ' Note that if you declare the lpData parameter as String, you must pass it By Value.
Private Sub Command1_Click()
End
End Sub
Private Sub Command2_Click()
On Error GoTo err
If Me.Combo1.Text <> "" Then
Dim s As String
s = Trim$(Me.Combo1.Text)
s = Right(s, Len(s) - 3)
Comport = CLng(s)
'frmIRdemo.Show
frmpc2lm.Show
Unload Me
End If
Exit Sub
err:
MsgBox err.Description
End Sub
Private Sub Form_Load()
Dim hKey As Long
Dim cnt As Long
Dim strkm As String
Dim strkv As String
Dim lenData As Long, typeData As Long
Me.Combo1.Text = ""
RegOpenKey HKEY_LOCAL_MACHINE, "Hardware\DeviceMap\SerialComm", hKey
strkm = String(255, Chr(0))
Do While RegEnumValue(hKey, cnt, strkm, 255, 0, ByVal 0&, ByVal 0&, ByVal 0&) = 0
'Debug.Print strkm
If RegQueryValueEx(hKey, strkm, 0, typeData, ByVal vbNullString, lenData) = 0 Then
strkv = String(lenData, Chr(0))
RegQueryValueEx hKey, strkm, 0, typeData, ByVal strkv, lenData
'Debug.Print strkv
If strkv <> "" Then Me.Combo1.AddItem Trim$(strkv)
End If
cnt = cnt + 1
Loop
Me.Combo1.ListIndex = 0
End Sub
运行情况如下:
图3 运行情况
文章评论(0条评论)
登录后参与讨论