电脑断网情况下,自动连接wifi

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhanghui_hn/article/details/88586077

  新买的win10笔记本,开机时不能自动连接家里wifi,在网上也找不到好的解决方案,无奈自行写代码实现。
  流程逻辑是:在while循环中,判断当前电脑是否联网,如果不联网,则执行"netsh wlan connect wifiName"命令,连接名为wifiName的wifi。

  程序编译后,运行的命令如下,interval参数表示“间隔多久时间检测一次是否联网”;wifi参数是表示“需要连接的wifi名”。下面命令的意思:每次15秒检测联网状态,连接的wifi名是wingedflyer

./AutoConnectWifi.exe --interval 15 --wifi "wingedflyer"
程序代码
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;

namespace AutoConnectWifi
{
    class Program
    {
        [DllImport("wininet.dll", EntryPoint = "InternetGetConnectedState")]

        //if network is okay, return true; otherwise return false;
        public extern static bool InternetGetConnectedState(out int conState, int reder);

        private const string argInterval = "--interval";
        private const string argWifi = "--wifi";

        static void Main(string[] args)
        {
            #region parse arguments
            int interval = 10;
            string wifiName = string.Empty;

            if (args != null && args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == argInterval)
                    {
                        if (i + 1 < args.Length)
                        {
                            int.TryParse(args[i + 1], out interval);
                        }
                    }
                    else if (args[i] == argWifi)
                    {
                        if (i + 1 < args.Length)
                        {
                            wifiName = args[i + 1];
                        }
                    }
                }
            }
            #endregion

            int connectState = -1;

            #region connect wifi in loop
            while (!string.IsNullOrWhiteSpace(wifiName))
            {
                Console.Write(DateTime.Now.ToString("HH:mm:ss"));

                if (InternetGetConnectedState(out connectState, 0))
                {
                    Console.WriteLine(" network is okay");
                }
                else
                {
                    Console.WriteLine($" connect wifi : {wifiName}");
                    ConnectWifi(wifiName);
                }

                Thread.Sleep(1000 * interval);
            }
            #endregion
        }

        /// <summary>
        /// connect wifi
        /// </summary>
        /// <param name="wifiName"></param>
        private static void ConnectWifi(string wifiName)
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            cmd.StartInfo.Arguments = $"/C netsh wlan connect {wifiName}";
            cmd.Start();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/zhanghui_hn/article/details/88586077