Verificare lo stato della connessione Internet
Un problema molto comune è quello di verificare se c’è connessione ad Internet sul computer su cui stiamo eseguendo il nostro programma Windows.
Un metodo molto interessante è quello di utilizzare una API di sistema che restituisce lo stato della connessione Internet. La API di cui stiamo parlando è InternetGetConnectedState contenuta nella libreria wininet.dll. Per utilizzarla con .NET sarà necessario referenziare il namespace System.Runtime.InteropServices e definire il prototipo della funzione. Ecco un esempio in C#
using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace InternetConnectionState { public partial class Form1 : Form { [DllImport("WININET", CharSet = CharSet.Auto)] static extern bool InternetGetConnectedState(ref ConnectionState lpdwFlags, int dwReserved); [Flags] enum ConnectionState : int { INTERNET_CONNECTION_MODEM = 0x1, INTERNET_CONNECTION_LAN = 0x2, INTERNET_CONNECTION_PROXY = 0x4, INTERNET_RAS_INSTALLED = 0x10, INTERNET_CONNECTION_OFFLINE = 0x20, INTERNET_CONNECTION_CONFIGURED = 0x40 } public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ConnectionState Description = 0; txtConnectionFlag.Text = InternetGetConnectedState(ref Description, 0).ToString(); txtConnectionState.Text = Description.ToString(); } } }










