Checking if User is connected to Internet or Not using Win32 API and C#

In application like Messenger or Application that provides automatic update need to check that user is connected to internet or not before proceeding further.

so we need to check whether  he is connected to internet or not we can check that with use of WIN32 API.

we can use Win32 API Wininet.dll 'sInternetGetConnectedState() method to check Internet Status 

for working with Pinvoke we need to add name space 

using System.Runtime.InteropServices;

now we need to write prototyping of the function  like below

[DllImport("wininet.dll")]

private extern static bool InternetGetConnectedState(outint connectionDescription, int reservedValue);
 

Now simply we can use this function to check internet connectivity 
 

take one button and label on form In buttons's click even write following code 

       

private void btnCheckConnection_Click(objectsender, EventArgs e)

        {

            int Description=0;

            bool isConnected = InternetGetConnectedState(out Description, 0);

            if (isConnected == true)

            {

                label1.Text = "User is Connected to Internet ";

            }

            else

            {

                label1.Text = "Disconnected";

            }

        }

8-7-2010 9-10-40 AM.gif

Here is how complete code look like 

-----------------------------------------------

 

public partial class Form1 : Form

{

  [DllImport("wininet.dll")]

  private extern static bool InternetGetConnectedState(out int connectionDescription,int reservedValue);

       

        public Form1()

        {

            InitializeComponent();

        }

  

        private void btnCheckConnection_Click(object sender, EventArgs e)

        {

            int Description=0;

            bool isConnected = InternetGetConnectedState(out Description, 0);

            if (isConnected == true)

            {

                label1.Text = "User is Connected to Internet ";

            }

            else

            {

                label1.Text = "Disconnected";

            }

        }

    }

Thank you.


Similar Articles