C#wpf 显示时间, 测试网络,线程简单使用(13)

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

测试时成功的,有问题联系我,大家一起交流学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值