views:

59

answers:

3

I am writing an application that checks if the computer is connected to one particular network or not, and does some magic for our users.

The application will run in the background and perform the check if the user requests it (menu in tray). I also want the application to automatically check and do magic if the user changes from wired to wireless, or disconnects and connects to a new network.

Is it possible to make it trigger when a network interface changes state?

+2  A: 

You should try System.Net.NetworkInformation namespace, or by using P/Invoke.

Samples:

Rubens Farias
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged); NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(NetworkChange_NetworkAddressChanged);
EricLaw -MSFT-
Unfortunately, nothing in that namespace is able to tell you when your WiFi signal drops to zero level, for example. That is, when NetworkAvailabilityChanged event occurs with its IsAvaiable property set to false, you know for sure that you're disconnected. But you might be disconnected (someone cut your cable, for instance) and no events occur. That's the way TCP/IP is working.
Igor Korkhov
A: 

The only reliable way of doing it is to periodically check availability of some reliable external resource. You can, for example, ping your server, request some info, etc.

Igor Korkhov
I am simply just pinging to see if our web proxy server responds, as the proxy configuration is what will be changed.My application is checking this every couple of minutes now, but I would love to make this happen instantly if the user connects to another network. :)
tkalve
Then the Rubens' method is what you need. But remeber, your users might potentially be connected to your proxy and some external network *at the same time*. Then if they disconnect from you proxy, NetworkAvailabilityChanged will not be raised, provided they are still connected to the other network.
Igor Korkhov
A: 
[DllImport("wininet.dll", SetLastError=true)] 
public static extern bool InternetGetConnectedState(out int flags,int reserved);

Returns TRUE if there is an Internet connection, or FALSE otherwise

igor