技术开发 频道

快速浏览Silverlight3 Beta:在线与离线状态检测

  【IT168 技术文档】在Silverlight3中提供了NetworkChange,NetworkInterface这两个类(均为abstract型),其中实现了NetworkAddressChanged的事件处理器用来检测当前在线状态,而NetworkInterface类的 GetIsNetworkAvailable()方法(返回bool类型),用来判断当前是否在线。有了这两个类,就可以很方便的实现动态检测当前应用是否连线了。

  下面就是我写的一个DEMO,用于演示如何使用这两个方法,其中的XAML代码如下:

<UserControl x:Class="Off_Online.MainPage"
    xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
    Width
="400" Height="300">
    
<Grid x:Name="LayoutRoot" Background="White">
        
<Grid.RowDefinitions>
            
<RowDefinition Height="150" />
            
<RowDefinition Height="150" />
        
</Grid.RowDefinitions>
        
<Image Width="100" Height="100" x:Name="StateIcon"  Grid.Row="0" HorizontalAlignment="Center" />
        
<TextBlock Name="NetWorkState" Foreground="Red" FontSize="20" Grid.Row="1" FontWeight="Bold"  HorizontalAlignment="Center" >当前状态未知</TextBlock>
    
</Grid>
</UserControl>

  而相应的CS代码如下:    

using System.Net.NetworkInformation;

namespace Off_Online
{
    
public partial class MainPage : UserControl
    {
        
public MainPage()
        {
            InitializeComponent();
            
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        
void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            NetworkChange.NetworkAddressChanged
+= OnNetworkAddressChanged;

            UpdateNetWorkState();
        }

        
void UpdateNetWorkState()
        {
            
string state = NetworkInterface.GetIsNetworkAvailable() ? "Online" : "Offline";
            StateIcon.Source
= new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/" + state + ".jpg", UriKind.Relative));
            NetWorkState.Text
= NetworkInterface.GetIsNetworkAvailable() ? "在线" : "离线";
        }
      
        
void OnNetworkAddressChanged(object sender, EventArgs e)
        {
             UpdateNetWorkState();
        }
    }
}

  下面就是其运行效果,首先是在线状态:


    
  然后拔掉网线,就会显示离线状态了:

0
相关文章