Visual Basic.net 检测网络连接状态的两种方法

来源:互联网 发布:家用粉碎机知乎 编辑:程序博客网 时间:2024/05/23 10:44
一.简单实现检测网络连接状态
Public Class Form1    '获取网络连接状态    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click        If My.Computer.Network.IsAvailable = True Then            Me.TextBox1.Text = "计算机已连接到网络上"        Else            Me.TextBox1.Text = "计算机未连接到网络上"        End If    End SubEnd Class
二.用wininet.dll判断网络是否正常连接的方法
作者没有采用.Net自己提供的My.Computer.Network.IsAvailable去判断网络是否正常连接,而是调用了Wininet.dll来判断。
代码如下:
Imports SystemImports System.Runtime.InteropServicesImports System.Text''' <summary>''' Determine whether or not there is a connection to the Internet present on the local machine.''' </summary>''' <remarks></remarks>Public Class InternetConnectionCheck    <DllImport("WININET", CharSet:=CharSet.Auto)> _    Private Shared Function InternetGetConnectedState(ByRef lpdwFlags As InternetConnectionState, ByVal dwReserved As Integer) As Boolean    End Function    <Flags()> _    Public Enum InternetConnectionState As Integer        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    ''' <summary>    ''' Call this function to know whether the internet is connected or not.    ''' </summary>    ''' <returns>Boolean</returns>    ''' <remarks></remarks>    Public Shared Function IsInternetConnected() As Boolean        Dim flags As InternetConnectionState = 0        Try            If InternetGetConnectedState(flags, 0) Then                Return True            Else                Return False            End If        Catch ex As Exception            Throw ex        Finally            flags = Nothing        End Try    End FunctionEnd Class


0 0