Windows 7 網絡資源管理

作者: Gnie  來源: 博客園  發布時間: 2011-01-16 18:18  閱讀: 1332 次  推薦: 0   原文鏈接   [收藏]  

  平時我們的計算機會連接很多種網絡類型:有線網、無線網、VPN。每種網絡類型可能又包含不同的網絡資源。在Windows 7 中保存著所有用戶已連接過的網絡資源。本篇將通過Windows API Code Pack 獲取這些網絡資源的屬性及詳細信息。

  首先新建一個項目,在其中引入WindowsAPICodePack.dll。打開XAML代碼,添加<TabControl> 將所有的網絡資源以標簽形式存放其中。

<Grid>
    <TabControl Margin="11,10,11,11" x:Name="tabControl" />
</Grid>

  在C#中加入using Microsoft.WindowsAPICodePack.Net 命名空間。編寫一個AddProperty() 方法,用來往Tab標簽里添加網絡屬性和信息。

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);
}

  接下來編寫一個LoadNetworkConnections() 方法,用它來加載Windows 7 中存儲的網絡資源。通過NetworkCollection 類可以獲得本機中所有網絡資源信息。利用NetworkConnectivityLevels 可以選擇All、Connected、Disconnected 三種不同的狀態模式。本例中我們選取所有的網絡資源(All)。隨后遍歷這些網絡資源,并創建相應的TabItem 標簽,將網絡資源屬性通過上面創建的AddProperty() 方法添加到標簽。

private void LoadNetworkConnections()
{
    NetworkCollection networks = NetworkListManager.GetNetworks(NetworkConnectivityLevels.All);

    foreach (Network n in networks)
    {
        TabItem tabItem = new TabItem();
        tabItem.Header = string.Format("Network {0} ({1})", tabControl.Items.Count, n.Name);
        tabControl.Items.Add(tabItem);

        StackPanel stackPanel = new StackPanel();
        stackPanel.Orientation = Orientation.Vertical;

        AddProperty("Name: ", n.Name, stackPanel);
        AddProperty("Description: ", n.Description, stackPanel);
        AddProperty("Domain type: ", n.DomainType.ToString(), stackPanel);
        AddProperty("Is connected: ", n.IsConnected.ToString(), stackPanel);
        AddProperty("Is connected to the internet: ", n.IsConnectedToInternet.ToString(), stackPanel);
        AddProperty("Network ID: ", n.NetworkId.ToString(), stackPanel);
        AddProperty("Category: ", n.Category.ToString(), stackPanel);
        AddProperty("Created time: ", n.CreatedTime.ToString(), stackPanel);
        AddProperty("Connected time: ", n.ConnectedTime.ToString(), stackPanel);
        AddProperty("Connectivity: ", n.Connectivity.ToString(), stackPanel);

        tabItem.Content = stackPanel;
    }
}

  最后,只需要在MainWindow() 加入LoadNetworkConnections() 方法即可。

public MainWindow()
{
    InitializeComponent();
    LoadNetworkConnections();
}

  運行程序瀏覽下效果,本機所有網絡資源的詳細信息都將顯示出來供用戶參考。

networklist

  源碼下載:NetworkListMgr.zip

0
0
 
標簽:Windows 7
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()