Friday, February 8, 2008

Test User's Internet Connection in VB(kiểm tra kết nối internet trong visual basic)

As more and more of your applications become distributed across the Internet, you'll no doubt want to build in a way to determine if the current user is actually connected to the Web. Fortunately, the Windows API offers a quick and easy way to do so with the
code:
InternetGetConnectedState() function.This function uses the declaration syntax seen here
Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef dwflags As Long, _ ByVal dwReserved As Long) As Long

The function returns 1 if a connection exists and 0 if not. You can easily convert these values to their Boolean equivalents in VB. After the test, the dwflags parameter will indicate what type of connection the user has. You use bitwise comparisons to test for specific values. The dwflags constants are as follows:
code:
Private Const CONNECT_LAN As Long = &H2 Private Const CONNECT_MODEM As Long = &H1 Private Const CONNECT_PROXY As Long = &H4 Private Const CONNECT_OFFLINE As Long = &H20 Private Const CONNECT_CONFIGURED As Long = &H40

You can ignore the dwReserved parameter.To see how this function works, launch a new VB project, and drop a Command Button onto the default form. Right-click on the form and select View Code from the shortcut menu. When the IDE opens the Code window, enter the InternetGetConnectedState() function and constant declarations as shown above. Then, enter the following procedures:

code:
Public Function IsWebConnected(Optional ByRef ConnType As String) As Boolean Dim dwflags As Long Dim WebTest As Boolean ConnType = "" WebTest = InternetGetConnectedState(dwflags, 0&) Select Case WebTest Case dwflags And CONNECT_LAN: ConnType = "LAN" Case dwflags And CONNECT_MODEM: ConnType = "Modem" Case dwflags And CONNECT_PROXY: ConnType = "Proxy" Case dwflags And CONNECT_OFFLINE: ConnType = "Offline" Case dwflags And CONNECT_CONFIGURED: ConnType = "Configured" Case dwflags And CONNECT_RAS: ConnType = "Remote" End Select IsWebConnected = WebTest End Function Private Sub Command1_Click() Dim msg As String If IsWebConnected(msg) Then msg = "You are connected to the Internet via: " & msg Else msg = "You are not connected to the Internet." End If MsgBox msg, vbOKOnly, "Internet Connection Status" End Sub

Run this program and click the form's command button, the message box tells you if you're connected to the Internet and by what type of connection.

No comments: