C#WIFI搜索与连接
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 ssid
private 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();
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, , (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 security
Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList();
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);
}
}
} // 字符串转Hex
public 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 = ; i < byStr.Length; i++)
{
sb.Append(Convert.ToString(byStr[i], ));
} 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, );
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 = ;
public WlanClient.WlanInterface wlanInterface = null;
}
}
Form1.cs
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名称", , HorizontalAlignment.Left); //一步添加
this.wifiListOK.Columns.Add("wifiSSID", , HorizontalAlignment.Left); //一步添加
this.wifiListOK.Columns.Add("加密方式", , HorizontalAlignment.Left); //一步添加
this.wifiListOK.Columns.Add("信号强度", , 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 > )
{
ListView.SelectedIndexCollection c = wifiListOK.SelectedIndices;
MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
DialogResult dr = MessageBox.Show("确定要连接" + wifiListOK.Items[c[]].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, , (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();
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搜索与连接的更多相关文章
- wind10系统 Atheros AR9271 Wireless Network Adapter USBwifi无线网卡的驱动安装解决无法搜索wifi信号,连接wifi信号无法上网的问题
		一.解决无法搜索wifi信号的问题 卸载掉之前的驱动,上网下载其他的驱动程序安装. http://drivers.mydrivers.com/drivers/463_185289.htm 二.安装完后 ... 
- Android WiFi开发教程(二)——WiFi的搜索和连接
		在上一篇中我们介绍了WiFi热点的创建和关闭,如果你还没阅读过,建议先阅读上一篇文章Android WiFi开发教程(一)——WiFi热点的创建与关闭. 本章节主要继续介绍WiFi的搜索和连接. Wi ... 
- Python  wifi掉线重连接
		原理很简单,通过python执行dos命令 : ping 和 netsh 需要用到os和time模块 代码如下: >>> import os >>> print ' ... 
- Atitit 列出wifi热点以及连接
		Atitit 列出wifi热点以及连接 配置命令 >netsh wlan /?1 显示已经有的配置netsh wlan show profiles1 C:\Users\Administrato ... 
- linux下WIFI的AP搜索、连接方法
		wpa_supplicant -Dwext -ieth1 -c/etc/wpa_supplicant.conf &wpa_cli save_configwpa_cli reconfigure ... 
- 【Android Developers Training】 76. 用Wi-Fi创建P2P连接
		注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ... 
- Ubuntu14.04创建无线WiFi,android可以连接上网
		前提条件: ubuntu14.04 unity,已经通过有线连接到internet 一般环境下创建的wifi热点android设备是无法识别的,网上说通过ap-hotspot方式创建出来的热点手机可以 ... 
- wp———跳转系统设置页面的wifi、网络连接、蓝牙、飞行模式等
		通过 ConnectionSettingsType 的设置,可以跳转 到 wifi.蓝牙.飞行模式.以及网络连接 其他方案跳转 private async void Button_Click_1(ob ... 
- 旧手机作为USB无线网卡使用(分享WIFI、蓝牙连接)
		首先开启手机的WIFI或者蓝牙功能,建立访问互联网的连接,然后设置-更多-网络共享与便携热点,打开安卓手机USB网络共享功能,即可在计算机上通过手机(无电话卡.数据卡)访问互联网.而且此时手机一直在充 ... 
随机推荐
- 【codeforces 724E】Goods transportation
			[题目链接]:http://codeforces.com/problemset/problem/724/E [题意] 有n个城市; 这个些城市每个城市有pi单位的物品; 然后已知每个城市能卖掉si单位 ... 
- 工具-putty使用
			Ubuntu 下安装 OpenSSH Server 是无比轻松的一件事情,需要的命令只有一条 sudo apt-get install openssh-server 启动SSH服务: sudo /et ... 
- 【HDOJ 2063】过山车
			[HDOJ 2063]过山车 二分图最大匹配模板题 1女对n男 问匹配最大对数 代码例如以下: #include <iostream> #include <cstdlib> # ... 
- the rendering library is more recent than your version of android studio
			近期更新了自己Android Studio中的SDK到最新版本号,AS的一部分配置改动了. 然后 在打开布局文件的时候 会出现 渲染错误 Rendering problem the rendering ... 
- 剑指offer面试题14(Java版):调整数组顺序使奇数位于偶数的前面
			题目:输入一个整数数组.实现一个函数来调整该数组中数字的顺序.使得全部奇数位于数组的前半部分.全部偶数位于数组的后半部分. 1.基本实现: 假设不考虑时间复杂度,最简单的思路应该是从头扫描这个数组,每 ... 
- 2015.04.28,外语,读书笔记-《Word Power Made Easy》 12 “如何奉承朋友” SESSION 36
			1. the great and the small 拉丁词语animus(mind的意思),animus和另一个拉丁词根anima(life principle.soul.spirit),是许多单词 ... 
- Rails中关联数据表的添加操作(嵌套表单)
			很早就听说有Web敏捷开发这回事,最近终于闲了下来,可以利用业余的时间学些新东西,入眼的第一个东东自然是Ruby on Rails.Rails中的核心要素也就是MVC.ORM这些了,因此关于Rails ... 
- c#自己实现线程池功能(二)
			介绍 在上一篇c#自己实现线程池功能(一)中,我们基本实现了一个能够执行的程序.而不能真正的称作线程池.因为是上篇中的代码有个致命的bug那就是没有任务是并非等待,而是疯狂的进行while循环,并试图 ... 
- caioj1496: [视频]基于连通性状态压缩的动态规划问题:Manhattan Wiring
			%%%%orz苏大佬 虽然苏大佬的baff吸不得,苏大佬的梦信不得,但是膜苏大佬是少不得的囧 这题还是比较有收获的 哼居然有我不会做的插头DP 自己yy了下,2表示属于2的插头,3表示3的插头 假如当 ... 
- WebRTC学习与DEMO资源一览
			一. WebRTC学习 1.1 WebRTC现状 本人最早接触WebRTC是在2011年底,那时Google已经在Android源码中加入了webrtc源码,放在/external/webrtc/ ... 
