<Grid>
<TextBlock Text="2017年2月7日 17:49:28" FontSize="16" Name="tbkDate" Foreground="Black"/>
<Button Name="ce" HorizontalAlignment="Left" Margin="720,350,0,0" VerticalAlignment="Top">
<Image Source="C:\Users\用户\source\repos\Wpfwangluoceshi\Wpfwangluoceshi\image\logo.ico"></Image>
</Button>
</Grid>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Timer = System.Timers.Timer;
namespace Wpfwangluoceshi
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
Timer time = new Timer();
int countDown = 1;
public MainWindow()
{
InitializeComponent();
tbkDate.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
time.Interval = 1000;
time.AutoReset = true;
time.Elapsed += time_Elapsed;
time.Start();
}
//检测网络线程简单使用
private void time_Elapsed(object sender, ElapsedEventArgs e)
{
this.Dispatcher.Invoke(new Action(() =>
{
tbkDate.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss");
}));
if (!IsConnectInternet())
{
countDown--;
this.Dispatcher.Invoke(new Action(() =>
{
ce.ToolTip = "网络连接中断,请检查本机网络连接...";
}));
}
else
{
countDown = 1;
this.Dispatcher.Invoke(new Action(() =>
{
ce.ToolTip = "网络连接正常...";
}));
}
}
//是否连接网络
private bool IsConnectInternet()
{
int Description = 0;
return InternetGetConnectedState(Description, 0);
}
}
}
测试时成功的,有问题联系我,大家一起交流学习。