有时,上传数据和下载数据都需要用到网络,但是不知道程序是否已连接到网络,下面是简单测试是否已连接网络的小功能

1、在winform窗体上添加一个按钮和多选框

怎样用C#代码知道是否已连接网络

2、点击检查网络,触发事件,如果是有网络,则勾上网络状态,失败则提示

怎样用C#代码知道是否已连接网络

3、事件的源码

 private void button1_Click(object sender, EventArgs e)
        {
            System.Net.NetworkInformation.Ping ping;
            System.Net.NetworkInformation.PingReply res;
            ping = new Ping();
            try
            {
                res = ping.Send("www.baidu.com");   //相当于控制台ping www.baidu.com
                if (res.Status == IPStatus.Success)   //判断ping是否成功
                {
                    MessageBox.Show("已连接");
                    this.checkBox1.Checked = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("网络连接异常,请检查网络!");
                this.checkBox1.Checked = false;
            }
        }

相关文章:

  • 2022-12-23
  • 2021-11-09
  • 2021-12-16
  • 2022-12-23
猜你喜欢
  • 2021-11-14
  • 2021-06-22
  • 2021-11-12
  • 2021-10-11
  • 2021-05-12
  • 2021-05-23
  • 2021-10-08
相关资源
相似解决方案