基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态

在Windows7操作系统下,支持的网络类型越来越复杂,微软提供了WindowsAPICodePack来进行简化底层开发,

我们大家来亲自实践一下关于网络状态开发,基于WindowsAPICodePack

启动VS2010

基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态

基于WPF与.net4.0创建一个应用程序窗口,控件布局如下

基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态

并添加相关引用支持

基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态

插入以下代码,详细分析请见代码!

using System.Windows; using System.Windows.Controls; using System.Text; using Microsoft.WindowsAPICodePack.Net; namespace Microsoft.WindowsAPICodePack.Samples.NetworkDemo { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); LoadNetworkConnections(); } private void LoadNetworkConnections() { NetworkCollection networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All); foreach (Network n in networks) { // 创建 tab TabItem tabItem = new TabItem(); tabItem.Header = string.Format("Network {0} ({1})", tabControl1.Items.Count, n.Name); tabControl1.Items.Add(tabItem); // StackPanel stackPanel2 = new StackPanel(); stackPanel2.Orientation = Orientation.Vertical; // 列举所有信息 AddProperty("网络名称: ", n.Name, stackPanel2); AddProperty("网络类型: ", n.Description, stackPanel2); AddProperty("域类型: ", n.DomainType.ToString(), stackPanel2); AddProperty("是否连接: ", n.IsConnected.ToString(), stackPanel2); AddProperty("是否上网: ", n.IsConnectedToInternet.ToString(), stackPanel2); AddProperty("网络 ID: ", n.NetworkId.ToString(), stackPanel2); AddProperty("类别: ", n.Category.ToString(), stackPanel2); AddProperty("创建时间: ", n.CreatedTime.ToString(), stackPanel2); AddProperty("连接时间: ", n.ConnectedTime.ToString(), stackPanel2); AddProperty("连接: ", n.Connectivity.ToString(), stackPanel2); // StringBuilder s = new StringBuilder(); s.AppendLine("网络连接:"); NetworkConnectionCollection connections = n.Connections; foreach (NetworkConnection nc in connections) { s.AppendFormat("\n\t连接 ID: {0}\n\t类型: {1}\n\t是否连接: {2}\n\t 是否连接因特网: {3}\n", nc.ConnectionId, nc.DomainType, nc.IsConnected, nc.IsConnectedToInternet); s.AppendFormat("\t适配器 ID: {0}\n\t连接: {1}\n", nc.AdapterId, nc.Connectivity); } s.AppendLine(); Label label = new Label(); label.Content = s.ToString(); stackPanel2.Children.Add(label); tabItem.Content = stackPanel2; } } private void AddProperty(string propertyName, string propertyValue, StackPanel parent) { StackPanel panel = new StackPanel(); panel.Orientation = Orientation.Horizontal; Label propertyNameLabel = new Label(); propertyNameLabel.Content = propertyName; panel.Children.Add(propertyNameLabel); Label propertyValueLabel = new Label(); propertyValueLabel.Content = propertyValue; panel.Children.Add(propertyValueLabel); parent.Children.Add(panel); } private void Window_Loaded(object sender, RoutedEventArgs e) { } } }

运行,看看效果

基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态

基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态

基于Visual C#2010 与WPF开发Windows 7检测网络连接于状态