Get notified when internet is connected or disconn

2019-03-20 23:39发布

问题:

I have a desktop application in WPF and C# developed under the .Net 4.0 Client Framework that has to show or hide some data according to if internet is available or not on the PC. This means I have to be able to detect as soon as possible if the internet is disconnected or connected in order to react. (Example could be disconnect from a wireless network or unplugging the network cable)

As I researched a bit I found that an event exists in the class NetworkChange called NetworkAvailabilityChanged that fires every time the connection changes (link to docs).

I'm developing in a Windows 8 machine and when I try it there the event is not fired but when I run the app on Windows 7 the event is fired. As in the docs says with the framework 4.0 compatibility for that event is until Windows 7, but looking at the same event in the docs for framework 4.5 compatibility says windows 8 also.

The problem is that even if I switch the target framework of the project to 4.5 (which is not the idea) the event won't fire on Windows 8.

Are there any incompatibilities issues that I'm not realizing? Is there a better way to get notified when the connection changes?

I need if possible a solution for the Framework 4.0 client that works on Windows Vista, 7 and 8

回答1:

http://msdn.microsoft.com/en-us/library/ee264321(VS.85).aspx

I came across this link during the same research. It was much more helpful.



回答2:

The answe of @William Riley help me to find the way to do it.

Finally I come to the point using the Network List Manager from the Windows API through the COM implementation from Microsoft. (you can check some examples)

It is important to add the correct reference to the project:

Then just you can follow the example from the link, is really short and direct to the point.