当前位置:首页 » 程序代码 » 正文

VB编程:判断网络是否连接(检测网络是否连接上Internet)

有些程序需要判断电脑是否连接到网络,是连接上Internet,还是连接到局域网,还是通过代理服务器连接的,检测到电脑连接上网,就做出相应的动作....

本程序利用API函数InternetGet ConnectedStateEX 来实现判断检测网络是否连接上网。

先做一个模块Module1.bas,代码内容如下:
Public Declare Function InternetGetConnectedStateEx Lib "wininet.dll" Alias "InternetGetConnectedStateExA" (ByRef lpdwFlags As Long, ByVal lpszConnectionName As String, ByVal dwNameLen As Long, ByVal dwReserved As Long) As Long
Public Enum EIGCInternetConnectionState
  INTERNET_CONNECTION_MODEM = &H1&
  INTERNET_CONNECTION_LAN = &H2&
  INTERNET_CONNECTION_PROXY = &H4&
  INTERNET_RAS_INSTALLED = &H10&
  INTERNET_CONNECTION_OFFLINE = &H20&
  INTERNET_CONNECTION_CONFIGURED = &H40&
End Enum

Public Property Get InternetConnected(Optional ByRef eConnectionInfo As EIGCInternetConnectionState, Optional ByRef sConnectionName As String) As Boolean
  Dim dwFlags As Long
  Dim sNameBuf As String
  Dim lR As Long
  Dim iPos As Long
   
  sNameBuf = String$(513, 0)
  lR = InternetGetConnectedStateEx(dwFlags, sNameBuf, 512, 0&)
  eConnectionInfo = dwFlags
  iPos = InStr(sNameBuf, vbNullChar)
  If iPos > 0 Then
    sConnectionName = Left$(sNameBuf, iPos - 1)
  ElseIf Not sNameBuf = String$(513, 0) Then
    sConnectionName = sNameBuf
  End If
  InternetConnected = (lR = 1)
End Property


在窗体模块输入代码:
Dim eR As EIGCInternetConnectionState
Dim sMsg As String
Dim sName As String
Dim bConnected As Boolean

Private Sub Form_Load()
    ' 判断网络是否连接:
    bConnected = InternetConnected(eR, sName)

    If (eR And INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM Then
        sMsg = sMsg & "使用了调制解调器连接。" & vbCrLf
    End If
    If (eR And INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN Then
        sMsg = sMsg & "使用了局域网连接。" & vbCrLf
    End If
    If (eR And INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY Then
        sMsg = sMsg & "使用了代理服务器连接。" & vbCrLf
    End If
    If (eR And INTERNET_CONNECTION_OFFLINE) = INTERNET_CONNECTION_OFFLINE Then
        sMsg = sMsg & "网络处于离线状态。" & vbCrLf
    End If
    If (eR And INTERNET_CONNECTION_CONFIGURED) = INTERNET_CONNECTION_CONFIGURED Then
        sMsg = sMsg & "网络已经设置。" & vbCrLf
    Else
        sMsg = sMsg & "网络尚未设置。" & vbCrLf
    End If
    If (eR And INTERNET_RAS_INSTALLED) = INTERNET_RAS_INSTALLED Then
        sMsg = sMsg & "系统已经安装。" & vbCrLf
    End If
  
    If bConnected Then
        MsgBox "网络已连接:" & sName & vbCrLf & vbCrLf & sMsg
    Else
        MsgBox "网络未连接:" & sName & vbCrLf & vbCrLf & sMsg
    End If
End Sub

打赏 支付宝打赏 微信打赏

来源:济亨网

本文链接:http://wb86.com/post/29.html

VB代码  API  
    << 上一篇 下一篇 >>

    湘公网安备 43011102000514号 - 湘ICP备08100508号