windows 如何查看网络连接是否更改状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2200798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:53:03  来源:igfitidea点击:

How can I see if a network connection changes state?

c#windows.net-3.5

提问by tkalve

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?

是否可以在网络接口更改状态时触发它?

回答by Federico Rizzo

You should use System.Net.NetworkInformation

您应该使用System.Net.NetworkInformation

 NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler((sender, e, ...otherParametersIfYouWant) => AvailabilityChangedCallback(sender, e, ...)); 
private void AvailabilityChangedCallback(object sender, NetworkAvailabilityEventArgs e)
    {
        if (e.IsAvailable)
        {
        //Internet Connection is available   
        }
     }

For other informations check this

有关其他信息,请检查

回答by Igor Korkhov

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.

唯一可靠的方法是定期检查一些可靠的外部资源的可用性。例如,您可以 ping 您的服务器、请求一些信息等。