1. Use the internetgetconnectedstate Function
One disadvantage of this function is that it takes several seconds to respond to the problem.
2. Use the isnetworkalive Function
Network connectivity can be reflected in a timely manner, but the System Event Notification Service is required (the system automatically starts the service by default ). To use this function, you must install the latest SDK (for example,. net)
Two methodsCodeAs shown in the following figure, I have tested it from other places.
[Dllimport ( " Wininet. dll " )]
Private Static Extern Bool Internetgetconnectedstate ( Ref Int Dwflag, Int Dwreserved );
Private String Fun_internetgetconnectedstate ()
{
Int Internet_connection_modem = 1 ;
Int Internet_connection_lan = 2 ;
Int Internet_connection_proxy = 4 ;
Int Internet_connection_modem_busy = 8 ;
String Output = Null ;
Int32 flags = New Int (); // Internet access
Bool M_bonline = True ; // Online or not
M_bonline = Internetgetconnectedstate ( Ref Flags, 0 );
If (M_bonline) // Online
{
If (Flags & Internet_connection_modem) = Internet_connection_modem)
{
Output = " Online: dial-up Internet access \ n " ;
}
If (Flags & Internet_connection_lan) = Internet_connection_lan)
{
Output = " Online: via LAN \ n " ;
}
If (Flags & Internet_connection_proxy) = Internet_connection_proxy)
{
Output = " Online: proxy \ n " ;
}
If (Flags & Internet_connection_modem_busy) = Internet_connection_modem_busy)
{
Output = " Modem is occupied by other non-Internet connections \ n " ;
}
}
Else
{
Output = " Not online \ n " ;
}
Return Output;
}
[Dllimport ( " Sensapi. dll " )]
Private Extern Static Bool Isnetworkalive ( Out Int Connectiondescription );
Private String Fun_isnetworkalive ()
{
Int Network_alive_lan = 0 ;
Int Network_alive_wan = 2 ;
Int Network_alive_aol = 4 ;
String Output = Null ;
Int Flags; // Internet access
Bool M_bonline = True ; // Online or not
M_bonline = Isnetworkalive ( Out Flags );
If (M_bonline) // Online
{
If (Flags & Network_alive_lan) = Network_alive_lan)
{
Output = " Online: network_alive_lan \ n " ;
}
If (Flags & Network_alive_wan) = Network_alive_wan)
{
Output = " Online: network_alive_wan \ n " ;
}
If (Flags & Network_alive_aol) = Network_alive_aol)
{
Output = " Online: network_alive_aol \ n " ;
}
}
Else
{
Output = " Not online \ n " ;
}
Return Output;
}
Private Void Timereffectick ( Object Sender, eventargs E)
{
Label1.text = Fun_internetgetconnectedstate ();
Label2.text = Fun_isnetworkalive ();
}