Check for 'ActiveConnection' via WinInet

This bit of code will show you how to detect an active connection using the WinInet API.

I have seen many who use the Windows Registry to check for an active connection, this is fine but you also need to code for a Registry Wrapper or use a handy class like VBA's Registry one but this may cost you some size. So a convienent way is to use the winInet API to check for an active connection.

Dump this into a module and when you do something like 'Msgbox Connected()' you will get TRUE is its conencted and FALSE if it isn't.

Option Explicit
Private Declare Function InternetGetConnectedStateEx Lib "wininet.dll" Alias "InternetGetConnectedStateExA" (lpdwFlags As Long, lpszConnectionName As Long, dwNameLen As Long, ByVal dwReserved As Long) As Long

Public Function Connected() As Boolean

   Dim lNameLen            As Long
   Dim lRetVal             As Long
   Dim lConnectionFlags    As Long
   Dim LPTR                As Long
   Dim lNameLenPtr         As Long
   Dim sConnectionName     As String
   sConnectionName = Space$(256)
   lNameLen = 256
   LPTR = StrPtr(sConnectionName)
   lNameLenPtr = VarPtr(lNameLen)

   lRetVal = InternetGetConnectedStateEx(lConnectionFlags, ByVal LPTR, ByVal lNameLen, 0&)

   Connected = (lRetVal <> 0)
End Function

Smaller, reliable and most of all its using the Windows API which is far better than searching the Windows Registry for a certain KEY.

You might also like...


Thushan Fernando Senior Developer working at Readify on cool new technology and platforms.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“We better hurry up and start coding, there are going to be a lot of bugs to fix.”