原创 如何捕获MSComm控件的无效端口号出错(VB6.0)

2010-4-3 16:56 5929 4 4 分类: 软件与OS
如何捕获MSComm控件的无效端口号出错(VB6.0)

 



Private Function funCommPortDetect(PortNumber As Integer) As Integer
   
On Error Resume Next'//屏蔽错误
    MSComm0.CommPort = PortNumber'//指定端口号
    MSComm0.PortOpen = True'//打开端口
    If Err Then'//如果端口不存在产生错误
        funCommPortDetect = -1'//返回-1
    Else'//端口存在返回当前端口号
        funCommPortDetect = PortNumber
   
End If
    MSComm0.PortOpen
= False'//关闭打开的端口
End Function

Public Function CommPortFix() As String
   
Dim intCommPortNumber As Integer, blnFirst As Boolean
   
Dim strResult As String
   
On Error Resume Next    '//屏蔽错误
    For intCommPortNumber = 1 To 16'//一般机器上不超过16个串口
        If funCommPortDetect(intCommPortNumber) <> -1 Then
            strResult
= strResult & " " intCommPortNumber'//如果存在串口1,2,5.则结果strResult=1 2 5
        End If
   
Next
    CommPortFix
= strResult'//返回结果
End Function


调用的时候直接令一字符变量strString=CommPortFix()即可,得到的字符串自己可以用Split处理.如果想先预处理,返回一个数组的话可以如下定义CommPortFix()函数:


VB code

Public Function CommPortFix() As String()
Dim intCommPortNumber As Integer, blnFirst As Boolean
Dim strResult As String
On Error Resume Next '屏蔽错误
blnFirst = True
For intCommPortNumber = 1 To 16
If funCommPortDetect(intCommPortNumber) <> -1 Then
If blnFirst Then
strResult
= "COM" & intCommPortNumber
blnFirst
= False
Else
strResult
= strResult & " " & "COM" & intCommPortNumber
End If
End If
Next
CommPortFix
= Split(strResult, " ")
End Function

如果存在串口1,2,5,定义一个数组,Dim arrString() As String,arrString=CommPortFix().这样arrString(0)="COM1",arrString(1)="COM2",arrString(2)="COM5".



转自:http://topic.csdn.net/u/20080821/10/c324cb76-47c8-4410-b726-098e5b260d00.html

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
4
关闭 站长推荐上一条 /3 下一条