特别声明,本文转自:https://www.cnblogs.com/ywf520/p/6502452.html

1、功能搜索WIFI并连接

2、所用工具及资源:VS2012 Managed Wifi API(即:引用ManagedWifi.dll文件地址:http://files.cnblogs.com/files/ywf520/ManagedWifi.zip)

3、运行截图及工程截图:

工程目录 结构

4、具体代码实现

wifiSo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NativeWifi; namespace WifiConnect
{class wifiSo{private WIFISSID ssid;               //wifi ssidprivate string key;                 //wifi密码public List<WIFISSID> ssids = new List<WIFISSID>();public wifiSo(){ssids.Clear();}public wifiSo(WIFISSID ssid, string key)  {ssids.Clear();this.ssid = ssid;this.key = key;}//寻找当前连接的网络:public static string GetCurrentConnection(){WlanClient client = new WlanClient();foreach (WlanClient.WlanInterface wlanIface in client.Interfaces){Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);foreach (Wlan.WlanAvailableNetwork network in networks){if (wlanIface.InterfaceState == Wlan.WlanInterfaceState.Connected && wlanIface.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected){return wlanIface.CurrentConnection.profileName;}}}return string.Empty;}static string GetStringForSSID(Wlan.Dot11Ssid ssid){return Encoding.UTF8.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);}/// <summary>/// 枚举所有无线设备接收到的SSID/// </summary>public void ScanSSID(){WlanClient client = new WlanClient();foreach (WlanClient.WlanInterface wlanIface in client.Interfaces){// Lists all networks with WEP securityWlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);foreach (Wlan.WlanAvailableNetwork network in networks){WIFISSID targetSSID = new WIFISSID();targetSSID.wlanInterface = wlanIface;targetSSID.wlanSignalQuality = (int)network.wlanSignalQuality;targetSSID.SSID = GetStringForSSID(network.dot11Ssid);//targetSSID.SSID = Encoding.Default.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength);targetSSID.dot11DefaultAuthAlgorithm = network.dot11DefaultAuthAlgorithm.ToString();targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm.ToString();ssids.Add(targetSSID);}}} // 字符串转Hexpublic static string StringToHex(string str){StringBuilder sb = new StringBuilder();byte[] byStr = System.Text.Encoding.Default.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)for (int i = 0; i < byStr.Length; i++){sb.Append(Convert.ToString(byStr[i], 16));}return (sb.ToString().ToUpper());}// 连接到无线网络public void ConnectToSSID(){try{String auth = string.Empty;String cipher = string.Empty;bool isNoKey = false;String keytype = string.Empty;//Console.WriteLine("》》》《《" + ssid.dot11DefaultAuthAlgorithm + "》》对比《《" + "Wlan.Dot11AuthAlgorithm.RSNA_PSK》》");switch (ssid.dot11DefaultAuthAlgorithm){case "IEEE80211_Open":auth = "open"; break;case "RSNA":auth = "WPA2PSK"; break;case "RSNA_PSK"://Console.WriteLine("电子设计wifi:》》》");auth = "WPA2PSK"; break;case "WPA":auth = "WPAPSK"; break;case "WPA_None":auth = "WPAPSK"; break;case "WPA_PSK":auth = "WPAPSK"; break;}switch (ssid.dot11DefaultCipherAlgorithm){case "CCMP":cipher = "AES";keytype = "passPhrase";break;case "TKIP":cipher = "TKIP";keytype = "passPhrase";break;case "None":cipher = "none"; keytype = "";isNoKey = true;break;case "WWEP":cipher = "WEP";keytype = "networkKey";break;case "WEP40":cipher = "WEP";keytype = "networkKey";break;case "WEP104":cipher = "WEP";keytype = "networkKey";break;}if (isNoKey && !string.IsNullOrEmpty(key)){Console.WriteLine(">>>>>>>>>>>>>>>>>无法连接网络!");return;}else if (!isNoKey && string.IsNullOrEmpty(key)){Console.WriteLine("无法连接网络!");return;}else{//string profileName = ssid.profileNames; // this is also the SSID string profileName = ssid.SSID;string mac = StringToHex(profileName);string profileXml = string.Empty;if (!string.IsNullOrEmpty(key)){profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>{2}</authentication><encryption>{3}</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>{4}</keyType><protected>false</protected><keyMaterial>{5}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>",profileName, mac, auth, cipher, keytype, key);}else{profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><autoSwitch>false</autoSwitch><MSM><security><authEncryption><authentication>{2}</authentication><encryption>{3}</encryption><useOneX>false</useOneX></authEncryption></security></MSM></WLANProfile>",profileName, mac, auth, cipher, keytype);}ssid.wlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);bool success = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000);if (!success){Console.WriteLine("连接网络失败!");return;}}}catch (Exception e){Console.WriteLine("连接网络失败!");return;}}//当连接的连接状态进行通知 面是简单的通知事件的实现,根据通知的内容在界面上显示提示信息:private void WlanInterface_WlanConnectionNotification(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData){try{if (notifyData.notificationSource == Wlan.WlanNotificationSource.ACM){int notificationCode = (int)notifyData.NotificationCode;switch (notificationCode){case (int)Wlan.WlanNotificationCodeAcm.ConnectionStart:Console.WriteLine("开始连接无线网络.......");break;case (int)Wlan.WlanNotificationCodeAcm.ConnectionComplete:break;case (int)Wlan.WlanNotificationCodeAcm.Disconnecting:Console.WriteLine("正在断开无线网络连接.......");break;case (int)Wlan.WlanNotificationCodeAcm.Disconnected:Console.WriteLine("已经断开无线网络连接.......");break;}}//}));}catch (Exception e){//Loger.WriteLog(e.Message);}}}class WIFISSID{public string SSID = "NONE";public string dot11DefaultAuthAlgorithm = "";public string dot11DefaultCipherAlgorithm = "";public bool networkConnectable = true;public string wlanNotConnectableReason = "";public int wlanSignalQuality = 0;public WlanClient.WlanInterface wlanInterface = null;}
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NativeWifi;
using System.Threading;
namespace WifiConnect
{
    public partial class wifi : Form
    {
        private List<WIFISSID> ssids;
        private wifiSo wifiso;
        public wifi()
        {
            InitializeComponent();
        }

private void wifi_Load(object sender, EventArgs e)
        {
            
            wifiso = new wifiSo();  //加载wifi
            ssids = wifiso.ssids;
            wifiso.ScanSSID();      //显示所有wifi
            
        }
        private void connectWIFI()
        {

}

private void button1_Click(object sender, EventArgs e)
        {
            this.wifiListOK.Items.Clear();  //只移除所有的项。
            //wifiListOK.Clear();//清除listview中的数据
            SetwifiList();
            ScanSSID();
        }

//设置listviewok
        private void SetwifiList()
        {
            this.wifiListOK.Columns.Add("wifi名称", 160, HorizontalAlignment.Left); //一步添加 
            this.wifiListOK.Columns.Add("wifiSSID", 120, HorizontalAlignment.Left); //一步添加 
            this.wifiListOK.Columns.Add("加密方式", 100, HorizontalAlignment.Left); //一步添加
            this.wifiListOK.Columns.Add("信号强度", 88, HorizontalAlignment.Left); //一步添加 
            //ColumnHeader ch = new ColumnHeader();  //先创建列表头
            wifiListOK.GridLines = true;//显示网格
            wifiListOK.Scrollable = true;//显示所有项时是否显示滚动条
            wifiListOK.AllowColumnReorder = true;
            wifiListOK.FullRowSelect = true;
            wifiListOK.CheckBoxes = true;
        }
        //添加数据
        private void wifiListOKADDitem(String wifiname, String pass,String dot11DefaultAuthAlgorithm,int i)
        {
            this.wifiListOK.BeginUpdate();   //数据更新,UI暂时挂起,直到EndUpdate绘制控件,可以有效避免闪烁并大大提高加载速度  
            //this.wifiListOK.Items.Add(wifiname,0);
            ListViewItem wifiitem = wifiListOK.Items.Add(wifiname);

wifiitem.SubItems.Add(pass);
            wifiitem.SubItems.Add(dot11DefaultAuthAlgorithm);
            wifiitem.SubItems.Add(i+"");

this.wifiListOK.EndUpdate();  //结束数据处理,UI界面一次性绘制。
            this.wifiListOK.View = System.Windows.Forms.View.Details;
        }

//单击事件
        private void wifiListOK_SelectedIndexChanged(object sender, EventArgs e)
        {

if (wifiListOK.SelectedIndices != null && wifiListOK.SelectedItems.Count > 0)
            {
                ListView.SelectedIndexCollection c = wifiListOK.SelectedIndices;
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("确定要连接" + wifiListOK.Items[c[0]].Text + "吗?", "wifi连接", messButton);
                 if (dr == DialogResult.OK)//如果点击“确定”按钮
                 {
                    // Console.WriteLine("<<<<<<<<<<<<<<<<flags:{0}.>>>>>>>>>>>>>>>>>>>>>>>", ssid);
                     //wifiso.ConnectToSSID(targetSSID, "ZMZGZS520");//连接wifi
                 }
            }
        }
        static string GetStringForSSID(Wlan.Dot11Ssid ssid)
        {
            return Encoding.UTF8.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
        }
        //显示所有wifi
        public void ScanSSID()
        {
            WlanClient client = new WlanClient();
            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
            {
                // Lists all networks with WEP security
                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);
                foreach (Wlan.WlanAvailableNetwork network in networks)
                {
                    WIFISSID targetSSID = new WIFISSID();

targetSSID.wlanInterface = wlanIface;
                    targetSSID.wlanSignalQuality = (int)network.wlanSignalQuality;
                    targetSSID.SSID = GetStringForSSID(network.dot11Ssid);
                    //targetSSID.SSID = Encoding.Default.GetString(network.dot11Ssid.SSID, 0, (int)network.dot11Ssid.SSIDLength);
                    targetSSID.dot11DefaultAuthAlgorithm = network.dot11DefaultAuthAlgorithm.ToString();
                    targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm.ToString();
                    ssids.Add(targetSSID);
                    wifiListOKADDitem(GetStringForSSID(network.dot11Ssid), network.dot11DefaultCipherAlgorithm.ToString(),
                        network.dot11DefaultAuthAlgorithm.ToString(),(int)network.wlanSignalQuality);
                    if (GetStringForSSID(network.dot11Ssid).Equals("DZSJ1"))
                    {
                        var obj = new wifiSo(targetSSID, "ZMZGZS520");
                        Thread wificonnect = new Thread(obj.ConnectToSSID);
                        wificonnect.Start();
                        //wifiso.ConnectToSSID(targetSSID, "ZMZGZS520");//连接wifi
                        connectWifiOK.Text = GetStringForSSID(network.dot11Ssid);
                        Image img = new Bitmap(Environment.CurrentDirectory+"/image/wifi.png");//这里是你要替换的图片。当然你必须事先初始化出来图
                        pictureBoxW.BackgroundImage = img;
                        //Console.WriteLine(">>>>>>>>>>>>>>>>>开始连接网络!" + targetSSID.SSID + GetStringForSSID(network.dot11Ssid) + GetStringForSSID(network.dot11Ssid).Equals("DZSJ1"));
                    }

}
            }
        }
        /// <summary>
        /// 关闭wifi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void closeWIFI_Click(object sender, EventArgs e)
        {
            if (connectWifiOK.Text.Equals("无") || connectWifiOK.Text.Equals(null))
            {
                MessageBox.Show("当前无连接wifi");
            }
            else
            {
                
            }
        }
        //更新数据
        private void getwifidatabtn_Click(object sender, EventArgs e)
        {
            WifiSocket wifiscoket = new WifiSocket();
            wifiscoket.fuwu();
            wifiscoket.kehuduan();
        }
    }
}

5、到此就结束了,写的不对的地方希望大家多多指教,更多功能还希望小伙伴们继续研究。

6、鸣谢:感谢各位广大博友无私的分享精神!

7、参考:http://blog.csdn.net/m593192219/article/details/9363355

8、源代码:https://files.cnblogs.com/files/ywf520/ManagedWifi.zip

C#WIFI搜索与连接相关推荐

  1. Android WiFi开发教程(二)——WiFi的搜索和连接

    在上一篇中我们介绍了WiFi热点的创建和关闭,如果你还没阅读过,建议先阅读上一篇文章Android WiFi开发教程(一)--WiFi热点的创建与关闭. 本章节主要继续介绍WiFi的搜索和连接. Wi ...

  2. 无线抄表免费透传云服务器,两个WIFI模块USR-WIFI232-B2连接有人云实现远程一对一透传...

    本案例基于STA模式的无线网络配置: 数据流向:PC端串口调试软件----1号A2/B2设备-----有人云透传组----2号A2/B2设备---PC端串口调试软件 客户实际应用:串口设备---A2/ ...

  3. Linux 开发板4G转WiFi热点 手机连接热点上网(三 WiFi模块的移植及AP的建立)

    这里对WiFi模块的驱动就不做详细介绍,本篇文章可能会涉及两款WiFi模块,一个是USB接口的WiFi模块,一个是SDIO接口的wifi模块,即AP6212,平台可能涉及爱特梅尔和三星的4418两个平 ...

  4. Android官方开发文档Training系列课程中文版:连接无线设备之通过WIFI创建P2P连接

    原文地址:http://android.xsoftlab.net/training/connect-devices-wirelessly/wifi-direct.html#permissions Wi ...

  5. wifi传输信息需要连接服务器,基于近场通信的WiFi传输连接方案.pdf

    第39 卷 第6 期 计 算 机 工 程 2013 年6 月 Computer Engineering June 2013 Vol.39 No.6 文献标识码文献标识码::A 文献标识码文献标识码:: ...

  6. 华为wifi信号如何连接到服务器,如何解决华为路由器搜到信号却无法连接

    华为是世界上知名的通讯行业大品牌,你知道如何解决华为路由器搜到信号却无法连接吗?下面是学识网小编整理的一些关于如何解决华为路由器搜到信号却无法连接的相关资料,供你参考. 解决华为路由器搜到信号却无法连 ...

  7. 华为路由器显示连接到服务器失败怎么办,华为路由WS5200可以搜到wifi但无法连接怎么办...

    如果您在使用华为路由WS5200的时候可以搜索到路由器的 Wi-Fi 信号,但是无法连接的话,那么可能是因为出现了以下这些问题,快来看看有没有您遇到的那个吧! 搜到wifi但无法连接原因检查和解决方法 ...

  8. 计算机怎么添加隐藏的网络,win10怎么添加隐藏wifi?电脑连接隐藏wifi方法

    原标题:win10怎么添加隐藏wifi?电脑连接隐藏wifi方法 为了wifi的安全,有些用户将无线路由器的wifi设置为隐藏.如果需要连接,则需要自己手动追加,但是很多windows10系统用户不知 ...

  9. WeFi – 自动搜索并连接未加密的无线网络

    蹭网,相信很多拥有笔记本电脑的朋友,有意或无意中都做过,但是大部分却是手动搜索未加密的无线网络,然后连接上去,那么是否有这么一款工具,可以自动搜索没有密码的无线网络并自动连接呢?答案是肯定的.今天就给 ...

最新文章

  1. 计算机工程实践,【计算机工程论文】计算机工程实践能力培养(共3056字)
  2. 熊市利好,Bit-Z推出币圈最高返佣50%
  3. 017_python常用小技巧
  4. uni map 实时记录轨迹_国际学校纷纷引进MAP考试系统,到底有什么好处?
  5. 深入new/delete:Operator new的全局重载
  6. 使用 Redis的SETNX命令实现分布式锁
  7. Java学习笔记----线程
  8. js typeof 能得到哪几种类型
  9. backup exec linux卸载,Symantec Backup Exec 2012 Agent for Linux 卸载
  10. DelayQueue用例
  11. iOS获取设备ID总结
  12. 谈一谈Coders Programmer Developer的区别
  13. Data structure you've never heard of(枚举+dp)
  14. 销量“掉队”,零跑汽车火力全开
  15. 手柄xinput模式_玩家新宠,谷粒金刚PRO游戏手柄不全面体验
  16. 剧场小钢琴 – Performance Samples River Piano Kontakt
  17. 真的是会者不难,难者不会啊!
  18. MakerDao原理
  19. 打造引领世界湾区经济的新发展样板
  20. ASP.Net MVC开发基础学习笔记(3):Razor视图引擎、控制器与路由机制学习

热门文章

  1. jQuery 表单验证插件,jQuery Validation Engine用法详解
  2. OC-变量和数据类型
  3. PHP远程下载图片损坏问题
  4. 下一代Asp.net开发规范OWIN(2)—— Katana介绍以及使用
  5. 一个计算机高手的成长历程[转]
  6. 云迹科技:站在酒店场景服务机器人的风口
  7. 高通平台java层操作NV数据的方法
  8. 高通平台device tree生成platform device的过程(MSM8909)
  9. HP QC IE11不支持( win7 64位 无法安装)解决方法
  10. 大数据可视化html模板开源_5个最受工程师欢迎的大数据可视化工具