NetworkInformationクラスのConnectionProfile.GetNetworkConnectivityLevelメソッドを使うとNetworkConnectivityLevelが取得できます。この値は以下のとおりですが、
- None
- LocalAccess
- ConstrainedInternetAccess
- InternetAccess
// using Windows.Networking.Connectivity;
private bool CheckInternetConnection()
{
var profile = NetworkInformation.GetInternetConnectionProfile();
if (profile == null)
return false;
return (profile.GetNetworkConnectivityLevel() >= NetworkConnectivityLevel.InternetAccess);
}
インターネット接続状況の変化はNetworkInformation.NetworkStatusChangedイベントで分かるので、簡単なWPFのサンプルアプリとしては以下のようになります。using System;
using System.ComponentModel;
using System.Windows;
using Windows.Networking.Connectivity;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public bool IsInternetConnected
{
get { return (bool)GetValue(IsInternetConnectedProperty); }
set { SetValue(IsInternetConnectedProperty, value); }
}
public static readonly DependencyProperty IsInternetConnectedProperty =
DependencyProperty.Register(
"IsInternetConnected",
typeof(bool),
typeof(MainWindow),
new PropertyMetadata(false));
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
IsInternetConnected = CheckInternetConnection();
NetworkInformation.NetworkStatusChanged += OnNetworkStatusChanged;
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged;
}
private void OnNetworkStatusChanged(object sender)
{
this.Dispatcher.Invoke(() => IsInternetConnected = CheckInternetConnection());
}
private bool CheckInternetConnection()
{
var profile = NetworkInformation.GetInternetConnectionProfile();
if (profile == null)
return false;
return (profile.GetNetworkConnectivityLevel() >= NetworkConnectivityLevel.InternetAccess);
}
}
この他にもWinRTにはデスクトップアプリでも使える機能がちょこちょこあるので、Windowsストアアプリに興味がなくても知っておくと便利なことがあります。
0 コメント :
コメントを投稿