none
Network Connection Detection C# RRS feed

  • Question

  • Hi,
    I have been trying to have my application looking for a connection

    I have this code in my public MainForm() after InitializeComponent();



    ManagementClass newClass = new ManagementClass();
                ManagementEventWatcher networkAdapterArrivalWatcher =
                new ManagementEventWatcher("\\root\\wmi",
                "SELECT * FROM MSNdis_NotifyAdapterArrival ");
                ManagementEventWatcher networkAdapterRemovalWatcher =
                new ManagementEventWatcher("\\root\\wmi",
                "SELECT * FROM MSNdis_NotifyAdapterRemoval ");
                MyHandler handler = new MyHandler();
                networkAdapterArrivalWatcher.EventArrived += new EventArrivedEventHandler(handler.Arrived);
                networkAdapterRemovalWatcher.EventArrived += new EventArrivedEventHandler(handler.Removed);
                networkAdapterArrivalWatcher.Start();
                networkAdapterRemovalWatcher.Start();
                while (true)
                    System.Threading.Thread.Sleep(200000);
    and I have this code in public partial class MainForm : Form { ... }


     public class MyHandler
            {
                public void Arrived(object sender, EventArrivedEventArgs e)
                {
                    Console.WriteLine("Network connected");
                    MessageBox.Show("Test");
                }
    
                public void Removed(object sender, EventArrivedEventArgs e)
                {
                    Console.WriteLine("Network disconnected");
                    MessageBox.Show("Test");
                }
    
            }
    but when I disconnect my cable or connect it, nothing happens.
    Anyone has any input ? Am I loading the code at the wrong spot ?

    Thanks for help
    Tuesday, July 21, 2009 5:53 PM

Answers

  • NetowrkChange.NetworkAvailabilityChanged does continuously monitor.  I just tested it.  I added a simple form, with nothing in it, and put the following code in the form:

    using System.Net.NetworkInformation;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication24
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                NetworkChange.NetworkAvailabilityChanged += AvailabilityChanged;
            }
    
            private void AvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
            {
                if (e.IsAvailable)
                    MessageBox.Show("Network connected!");
                else
                    MessageBox.Show("Network disconnected!");
            }
        }
    }
    I then unplugged the network cable, and a few seconds later, received a "Network Disconnected" MessageBox.  I plugged it back in, and received a MessageBox saying "Network Connected".
    David Morton - http://blog.davemorton.net/ - @davidmmorton - ForumsBrowser, a WPF MSDN Forums Client
    • Marked as answer by nobugz Tuesday, July 21, 2009 8:51 PM
    Tuesday, July 21, 2009 7:06 PM

All replies

  • I think you're overcomplicating here. 

    Use the NetworkChange class.

    Instead of using the whole WMI scenario, you could simply use:

    NetworkChange.NetworkAvailabilityChanged += AvailabilityChanged;

    Then you could have a method to handle this:

    private void AvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
    {
         if (e.IsAvailable)
              MessageBox.Show("Network connected!");
         else
              MessageBox.Show("Network disconnected!");
    }

    Use either Console.WriteLine or MessageBox.Show. There's no need for both. If you're in a WinForms app, MessageBox.Show will work just fine.

    Lastly, eliminate the while(true) loop.  Just let the form show itself.  If it's not staying open, use ShowDialog instead of Show.  This is probably the root of your percieved problem.
    David Morton - http://blog.davemorton.net/ - @davidmmorton - ForumsBrowser, a WPF MSDN Forums Client
    Tuesday, July 21, 2009 5:58 PM
  • Thanks for the input,
    But what I don't understand is that with the AvailibityChanged way it would 'seat' there as a monitor yes ?
    i want a way that is continously monitoring,

    i tested it and it seems like it does the monitoring thing,
    but how does the availability thing work ? i mean i don't see any 'loop' so how does it continously check for a change ?

    thanks
    Tuesday, July 21, 2009 7:01 PM
  • NetowrkChange.NetworkAvailabilityChanged does continuously monitor.  I just tested it.  I added a simple form, with nothing in it, and put the following code in the form:

    using System.Net.NetworkInformation;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication24
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                NetworkChange.NetworkAvailabilityChanged += AvailabilityChanged;
            }
    
            private void AvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
            {
                if (e.IsAvailable)
                    MessageBox.Show("Network connected!");
                else
                    MessageBox.Show("Network disconnected!");
            }
        }
    }
    I then unplugged the network cable, and a few seconds later, received a "Network Disconnected" MessageBox.  I plugged it back in, and received a MessageBox saying "Network Connected".
    David Morton - http://blog.davemorton.net/ - @davidmmorton - ForumsBrowser, a WPF MSDN Forums Client
    • Marked as answer by nobugz Tuesday, July 21, 2009 8:51 PM
    Tuesday, July 21, 2009 7:06 PM
  • Hi,
    yes sorry
    My post was not proper and updated shortly after so you probably did not see the update.
    My question was 'how' does it monitor without a loop of any sort with just one line ?

    Thanks your help was very helpfull

    Tuesday, July 21, 2009 7:15 PM
  • At it's heart, it hooks into WinSock using the WSAEventSelect function, which raises an event when the IP address changes, which it would do when the computer loses connectivity.  Both the NetworkAddressChanged and NetworkAvailabilityChanged events use this method, although in the case of the NetworkAvailabilityChanged event, when the IP address changes, it calls the internal method "SystemNetworkInterface.InternalGetIsNetworkAvailable()", which checks the OperationalStatus of each interface that's not a Tunnel or Loopback interface, and returns true if one of those interfaces is found to be "Up", and false if not.  If it returns false, then the network is not available, and the user-specified event is raised.  That's it in a nutshell.  For the full analysis, you could look at it through Reflector.

    Here's a link to the WSAEventSelect function on MSDN:

    http://msdn.microsoft.com/en-us/library/ms741576(VS.85).aspx
    David Morton - http://blog.davemorton.net/ - @davidmmorton - ForumsBrowser, a WPF MSDN Forums Client
    Tuesday, July 21, 2009 7:31 PM
  • Thanks for the summary,
    i will download reflector to see if i can understand anything :)
    regards
    Tuesday, July 21, 2009 8:16 PM
  • NetowrkChange.NetworkAvailabilityChanged does continuously monitor.  I just tested it.  I added a simple form, with nothing in it, and put the following code in the form:

    using System.Net.NetworkInformation;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication24
    {
      public partial class Form1 : Form
      {
        public Form1()
        {
          InitializeComponent();
          NetworkChange.NetworkAvailabilityChanged += AvailabilityChanged;
        }
    
        private void AvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
        {
          if (e.IsAvailable)
            MessageBox.Show("Network connected!");
          else
            MessageBox.Show("Network disconnected!");
        }
      }
    } 
    
    Can someone help? The above does not work for me. Using Visual Studio 2010, Windows 7 64 on a HP Probook laptop. I created a blank Windows Forms project, and copied the above into the project. Debugger shows the line in the form constructor is executed, but the event never fires when I unplug or restore the network cable. I placed a breakpoint on the if(e.IsAvailable), and execution does not break there, neither do I get one of the two messages; but I do see the change in the Taskbar's notification, area, and I confirmed with ping tests. Machine has a static IP adress, so doing an IPConfig confirmed the IP address did not change to 127.0.0.1 on unplugging: only the availability changed.
    Monday, August 29, 2011 9:40 AM
  • Code Producer,

    Have you found an answer to your delimina yet?  I have the same version of Visual Studio and the same OS as you, I am having the outcome.  No application response to the event.

     

    Thank you

    Tuesday, October 11, 2011 4:48 PM
  • The NetworkAvailabilityChanged event only occurs when ALL networks are offline.

    Try to listen to the NetworkAddressChanged Event.

    http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.aspx

     

    Wednesday, October 12, 2011 7:30 PM