自windows vista和windows XP SP2以后的版本,微软支持使用Native wifi API来连接和管理无线网络。不过官方文档中有句话:Ad hoc mode might not be available in future versions of Windows. Starting with Windows 8.1 and Windows Server 2012 R2, use Wi-Fi Direct instead.高级模式将不被支持。从Windows 8.1和Windows Server 2012 R2开始,请使用Wi-Fi Direct替代。这个我们暂时先不用理会。

Native wifi API可以的下载地址:http://download.csdn.net/detail/libby1984/9529224

下面是代码:

判断电脑是否连接上了网络:

        [DllImport("wininet")]private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);/// <summary>/// 检测本机是否联网/// </summary>/// <returns></returns>public static bool IsConnectedInternet(){int i = 0;if (InternetGetConnectedState(out i, 0)){//已联网return true;}else{//未联网return false;}}

扫描无线网络,首先实例化一个WlanClient的实例,遍历该实例中所有的WlanInterface。每一个WlanInterface 就是一个无线网络连接。然后遍历每个连接下搜索到的所有无线网络。如果WlanInterface的InterfaceState属性值为Connected,那么就表示该无线网络连接是当前连接的连接,如果想具体知道连接的是哪个无线网络,可以查看WlanInterface实例的CurrentConnection属性。下面代码中的WIFISSID类是记录netwoek参数的类,可以根据需要自己定义。

 /// <summary>  /// 枚举所有无线设备接收到的SSID  /// </summary>  private List<WIFISSID> ScanSSID(){WlanClient client = new WlanClient();List<WIFISSID> wifiList = new List<WIFISSID>();string conectedNetworkName = string.Empty;foreach (WlanClient.WlanInterface wlanIface in client.Interfaces){List<string> profileNames = new List<string>();// Lists all networks with WEP security  Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);foreach (Wlan.WlanAvailableNetwork network in networks){if (wlanIface.InterfaceState == Wlan.WlanInterfaceState.Connected && wlanIface.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected){conectedNetworkName = wlanIface.CurrentConnection.profileName;}WIFISSID targetSSID = new WIFISSID();if (network.networkConnectable){targetSSID.SSID = network.dot11Ssid;if (string.IsNullOrEmpty(network.profileName)){targetSSID.profileNames = GetStringForSSID(network.dot11Ssid);}else{targetSSID.profileNames = network.profileName;}if (!profileNames.Contains(targetSSID.profileNames)){profileNames.Add(targetSSID.profileNames);targetSSID.wlanInterface = wlanIface;targetSSID.wlanSignalQuality = (int)network.wlanSignalQuality;targetSSID.dot11DefaultAuthAlgorithm = network.dot11DefaultAuthAlgorithm;targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm.ToString();targetSSID.securityEnabled = network.securityEnabled;wifiList.Add(targetSSID);if (!string.IsNullOrEmpty(conectedNetworkName) && conectedNetworkName.Equals(network.profileName)){targetSSID.connected = true;}else{targetSSID.connected = false;}}}}}return wifiList;}public class WIFISSID
{public string profileNames;public Wlan.Dot11Ssid SSID;public NativeWifi.Wlan.Dot11AuthAlgorithm dot11DefaultAuthAlgorithm;public string dot11DefaultCipherAlgorithm = "";public bool networkConnectable = true;public string wlanNotConnectableReason = "";public int wlanSignalQuality = 0;public WlanClient.WlanInterface wlanInterface = null;public bool securityEnabled;public bool connected = false;
} 

寻找当前连接的网络:

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

连接到无线网络。连接到无线网络需要传无线网络配置文件,这个配置文件是一个XML,根据不同的网络配置文件中的参数不同。

下面的例子中的infoTB是界面上的一个TextBlock控件,用来显示提示信息,而Loger类是一个自定义类。各位可以根据自己的需要对显示提示信息的部分进行修改。

 /// <summary> /// 连接到无线网络/// </summary> /// <param name="ssid"></param> public void ConnectToSSID(WIFISSID ssid, string key) { try {String auth = string.Empty;String cipher = string.Empty; bool isNoKey = false;String keytype = string.Empty; switch (ssid.dot11DefaultAuthAlgorithm) { case Wlan.Dot11AuthAlgorithm.IEEE80211_Open: auth = "open"; break; //case Wlan.Dot11AuthAlgorithm.IEEE80211_SharedKey: // 'not implemented yet; //break; case Wlan.Dot11AuthAlgorithm.RSNA: auth = "WPA2PSK"; break; case Wlan.Dot11AuthAlgorithm.RSNA_PSK: auth = "WPA2PSK"; break; case Wlan.Dot11AuthAlgorithm.WPA: auth = "WPAPSK"; break; case Wlan.Dot11AuthAlgorithm.WPA_None: auth = "WPAPSK"; break; case Wlan.Dot11AuthAlgorithm.WPA_PSK: auth = "WPAPSK"; break; } switch (ssid.dot11DefaultCipherAlgorithm) { case Wlan.Dot11CipherAlgorithm.CCMP: cipher = "AES"; keytype = "passPhrase"; break; case Wlan.Dot11CipherAlgorithm.TKIP: cipher = "TKIP"; keytype = "passPhrase";break; case Wlan.Dot11CipherAlgorithm.None: cipher = "none"; keytype = ""; isNoKey = true; break; case Wlan.Dot11CipherAlgorithm.WEP: cipher = "WEP"; keytype = "networkKey"; break; case Wlan.Dot11CipherAlgorithm.WEP40: cipher = "WEP"; keytype = "networkKey"; break; case Wlan.Dot11CipherAlgorithm.WEP104:cipher = "WEP"; keytype = "networkKey"; break;}if (isNoKey && !string.IsNullOrEmpty(key)){infoTB.Text = "无法连接网络!";Loger.WriteLog("无法连接网络","SSID:" + this.ssid.SSID + "\r\n"+ "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"+ "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString());return;}else if (!isNoKey && string.IsNullOrEmpty(key)){infoTB.Text = "无法连接网络!";Loger.WriteLog("无法连接网络","SSID:" + this.ssid.SSID + "\r\n"+ "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"+ "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString());return;}else{string profileName = ssid.profileNames; // this is also the 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);//ssid.wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, ssid.profileNames);bool success = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000);if (!success){infoTB.Text = "连接网络失败!";Loger.WriteLog("连接网络失败","SSID:" + this.ssid.SSID + "\r\n"+ "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"+ "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString() + "\r\n");return;}} } catch (Exception e) {infoTB.Text = "无法连接网络!" + e.Message;Loger.WriteLog("无法连接网络","SSID:" + this.ssid.SSID + "\r\n"+ "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"+ "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString() + "\r\n"+ e.Message);return;} } 
如果想要了解连接无线网络过程中的细节,可以注册WlanInterface的WlanConnectionNotification事件。该事件会对当连接的连接状态进行通知,下面是简单的通知事件的实现,根据通知的内容在界面上显示提示信息:
    private void WlanInterface_WlanConnectionNotification(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData){try{this.Dispatcher.BeginInvoke(new Action(() =>{if (!this.ssid.profileNames.Equals(connNotifyData.profileName))  // 是否是当前SSID的通知{return;}if (notifyData.notificationSource == Wlan.WlanNotificationSource.ACM){int notificationCode = (int)notifyData.NotificationCode;switch (notificationCode){case (int)Wlan.WlanNotificationCodeAcm.ConnectionStart:Loger.WriteLog("开始连接无线网络" + this.ssid.profileNames);infoTB.Text = "开始连接无线网络......";break;case (int)Wlan.WlanNotificationCodeAcm.ConnectionComplete:Loger.WriteLog("连接无线网络成功" + this.ssid.profileNames);infoTB.Text = "连接无线网络成功!";this.DialogResult = true;break;case (int)Wlan.WlanNotificationCodeAcm.Disconnecting:Loger.WriteLog("正在断开无线网络连接" + this.ssid.profileNames);infoTB.Text = "正在断开无线网络连接......";break;case (int)Wlan.WlanNotificationCodeAcm.Disconnected:Loger.WriteLog("已经断开无线网络连接" + this.ssid.profileNames);infoTB.Text = "已经断开无线网络连接!";this.DialogResult = true;break;}}}));}catch (Exception e){Loger.WriteLog(e.Message);}}


使用ManagedWifi连接无线网络相关推荐

  1. linux命令行模式连接网络,centos命令行模式连接无线网络的过程

    1. 首先, 你的系统要能驱动无限网卡, 要是人品好的话, 系统已经自带了你的网卡的驱动程序. 不然就要先搞定无线网卡的驱动再说. 不然后面的步骤也就没必要了. 2. 看一下你的无线网卡叫什么: iw ...

  2. 解决Debian 9 iwlwifi固件缺失导致无法连接无线网络的问题

    解决Debian 9 iwlwifi固件缺失导致无法连接无线网络的问题 参考文章: (1)解决Debian 9 iwlwifi固件缺失导致无法连接无线网络的问题 (2)https://www.cnbl ...

  3. Ubuntu安装后无法连接无线网络

    [问题] Ubuntu安装后无法连接无线网络,无线连接的指示灯显示无线关闭状态(我的无线连接指示灯红灯位关闭,蓝色为开启),但是有线网络正常可用. [原因] 无线上网的驱动Ubuntu的无线上网驱动尚 ...

  4. android手机连接无线路由器上网设置,手机连接无线网络怎么设置?手机Wifi无线网设置教程...

    随着智能手机无线上网的流行,如今很多家庭都会组建Wifi无线网络,目前组建Wifi网络,大致有两种情况,一种是使用无线路由器,另外一种是将笔记本变身无线无路由器,从而实现智能手机也可以免费Wifi上网 ...

  5. linux 如何连接无线网卡,CentOS 7如何连接无线网络

    CentOS 7如何连接无线网络,虽然查阅了相关网络资料,但是以下内容均为原创内容,只有干货,无废话. 1.切换到超级用户 [Oscar@localhost 桌面]$ su root 2.查询可用的无 ...

  6. Windows Server 2012 解决无法连接无线网络

    刚安装的Windows Server 2012 R2,无线网卡已驱动,但不能连接无线网络上网: 打开服务器管理器,在"添加角色和功能"中添加"无线LAN服务" ...

  7. 笔记本计算机的连接无线网络连接,笔记本电脑连接wifi的方法步骤

    笔记本电脑怎么连接wifi?Wi-Fi是一种可以将个人电脑.手持设备(如pad.手机)等终端以无线方式互相连接的技术,事实上它是一个高频无线电信号.下面就由学习啦小编来给大家说说笔记本电脑怎么连接wi ...

  8. 笔记本计算机的连接无线网络连接,笔记本电脑怎么连无线_笔记本电脑连wifi怎么连-win7之家...

    大家都知道,只要有无线wifi覆盖的地方,笔记本电脑都可以随时随地的连接wifi进行上网,但是首先要连接上无线wifi才可以,很多小伙伴可能不知道笔记本电脑怎么连无线吧,其实方法很简单,接下来给大家讲 ...

  9. 计算机如何连接wifi台式,台式电脑怎么连接WIFI上网?台式电脑连接无线网络的方法...

    无线网络的覆盖非常广泛,小到大街小巷,大到各大商场,乃至居民小区.正常情况下,无线网络只能通过手机和笔记本电脑进行连接,若是需要使用台式电脑连接无线则需要另外加装无线网卡或者模块,阅读下文了解台式电脑 ...

最新文章

  1. 深度 | 学习如何学习的算法:简述元学习研究方向现状
  2. Wireshark EndPoints窗口
  3. 浅谈阿里云混合云的探索与实践
  4. 自制Win7安装U盘!
  5. SAP Commerce Cloud portal 的 deployment
  6. JAVA:贪吃蛇源代码
  7. python绘图 条形图 直方图 饼图 箱型图 误差图 多图绘制 图表注释 三维图形
  8. 每天一点Linux --- 在Linux终端下调用当前目录下的可执行文件时需要加上./的原因...
  9. 为用户增加sudo权限(修改sudoers文件)
  10. Java SE 基础:继承、封装、多态、fianl、static、abstract
  11. SharePoint开发错误—列表自定义表单出现“未将对象引用设置到对象的实例”
  12. Firefox在win10与win11系统上账号不同步的解决办法
  13. 什么事件必须要我王二狗来处理?
  14. iOS在UIButton中换行
  15. android wms布局过程,深入理解WMS
  16. python版FlappyBird代码解析
  17. Migrando电子商务可以实现Iluria para o Shopify(Python的标准)
  18. iOS 对接TopOn聚合广告心得
  19. 为什么手机充电时会感觉麻麻的,有问题吗?
  20. 思科网络安全 第十章测验答案

热门文章

  1. 计算机网络的有线接入,电脑怎么连接有线网络
  2. 黎曼的猜想 MySQL案例练习记录
  3. c语言程序设计1253,1253c语言程序设计a(2010年1月)
  4. 【腾讯QQ官方正式版下载】基于Internet的即时通信(IM)软件
  5. Android 高德地图黑屏定位,Android Fragment集成高德地图黑屏的问题解决方案
  6. 浅谈Android性能优化方案
  7. excel怎么把竖排变成横排_排版丑怎么办?5个方法拯救你
  8. vivo手机互传的文件怎么找到_小白换机最头疼文件转移!学会vivo互传这几个技巧,换机更轻松...
  9. quartz mysql 表 集群配置_Spring整合实战丨Quartz 集群配置
  10. C#实现自己的远程桌面控制工具