
如何用VB来检测当前电脑是否已经连接到网络呢?这需要用到我们VB编程语言 中的API函数。

在本程序中我们需要用到下面两个API内部函数。
Private Declare Function RasEnumConnections Lib "RasApi32.dll" Alias "RasEnumConnectionsA" (lpRasCon As Any, lpcb As Long, lpcConnections As Long) As Long
Private Declare Function RasGetConnectStatus Lib "RasApi32.dll" Alias "RasGetConnectStatusA" (ByVal hRasCon As Long, lpStatus As Any) As Long
虽然内容很长,但是我们不需要刻意去记忆,因为此函数是在我们的VB中的,直接调用即可。
代码如下:
Private Type vb1 ’自定义类型
dwSize As Long
hRasCon As Long
szEntryName(RMEN) As Byte
szDeviceType(RMDT) As Byte
szDeviceName(RMDN) As Byte
End Type
Private Type vb2 ’自定义类型
dwSize As Long
RasConnState As Long
dwError As Long
szDeviceType(RMDT) As Byte
szDeviceName(RMDN) As Byte
End Type

Public Function IfConnection() As Boolean ’自定义函数,返回网络连通的状态
Dim TRC(255) As RCN1
Dim le1 As Long
Dim lp As Long
Dim REv As Long
Dim Tss As RCN2
TRC(0).dwSize = 412
le1 = 256 * TRC(0).dwSize
REv = RasEnumConnections(TRC(0), le1, lp) ’调用函数
If REv <> 0 Then
MsgBox "错误!" ’警告
Exit Function
End If
Tss.dwSize = 160
REv = RasGetConnectStatus(TRC(0).hRasCon, Tss) ’调用函数
If Tss.RasConnState = &H2000 Then
IfConnection = True ’如果返回值为True则表示已连接
Else
IfConnection = False ’否则没有连通。
End If
End Function
Private Sub Command1_Click()
If IfConnection = True Then ’调用自定义函数
Label2.Caption = "本机目前已连接到Internet!"
End If
If IfConnection = False Then
Label2.Caption = "本机目前未连接Internet!"
End If
End Sub