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 = 0×1,
            INTERNET_CONNECTION_LAN = 0×2,
            INTERNET_CONNECTION_PROXY = 0×4,
            INTERNET_RAS_INSTALLED = 0×10,
            INTERNET_CONNECTION_OFFLINE = 0×20,
            INTERNET_CONNECTION_CONFIGURED = 0×40
        }

        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();
        }
    }
}

Sorgente dell’esempio

Lascia un commento

Categorie

Cerca

Meta