使用ManagedWifi连接无线网络

windows vistawindows 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.1Windows Server 2012 R2开始,请使用Wi-Fi Direct替代。这个我们暂时先不用理会。

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


下面是代码:

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

[csharp]  view plain  copy
  1. [DllImport("wininet")]  
  2. private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);  
  3.   
  4. /// <summary>  
  5. /// 检测本机是否联网  
  6. /// </summary>  
  7. /// <returns></returns>  
  8. public static bool IsConnectedInternet()  
  9. {  
  10.     int i = 0;  
  11.     if (InternetGetConnectedState(out i, 0))  
  12.     {  
  13.         //已联网  
  14.         return true;  
  15.     }  
  16.     else  
  17.     {  
  18.         //未联网  
  19.         return false;  
  20.     }  
  21. }  

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

[csharp]  view plain  copy
  1.     /// <summary>    
  2.         /// 枚举所有无线设备接收到的SSID    
  3.         /// </summary>    
  4.         private List<WIFISSID> ScanSSID()  
  5.         {  
  6.             WlanClient client = new WlanClient();  
  7.             List<WIFISSID> wifiList = new List<WIFISSID>();  
  8.             string conectedNetworkName = string.Empty;  
  9.             foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)  
  10.             {  
  11.                 List<string> profileNames = new List<string>();  
  12.                 // Lists all networks with WEP security    
  13.                 Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);  
  14.                 foreach (Wlan.WlanAvailableNetwork network in networks)  
  15.                 {  
  16.                     if (wlanIface.InterfaceState == Wlan.WlanInterfaceState.Connected && wlanIface.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected)  
  17.                     {  
  18.                         conectedNetworkName = wlanIface.CurrentConnection.profileName;  
  19.                     }  
  20.                       
  21.                     WIFISSID targetSSID = new WIFISSID();  
  22.                     if (network.networkConnectable)  
  23.                     {  
  24.                         targetSSID.SSID = network.dot11Ssid;  
  25.                         if (string.IsNullOrEmpty(network.profileName))  
  26.                         {  
  27.                             targetSSID.profileNames = GetStringForSSID(network.dot11Ssid);  
  28.                         }  
  29.                         else  
  30.                         {  
  31.                             targetSSID.profileNames = network.profileName;  
  32.                         }  
  33.   
  34.   
  35.                         if (!profileNames.Contains(targetSSID.profileNames))  
  36.                         {  
  37.                             profileNames.Add(targetSSID.profileNames);  
  38.                             targetSSID.wlanInterface = wlanIface;  
  39.                             targetSSID.wlanSignalQuality = (int)network.wlanSignalQuality;  
  40.                             targetSSID.dot11DefaultAuthAlgorithm = network.dot11DefaultAuthAlgorithm;  
  41.                             targetSSID.dot11DefaultCipherAlgorithm = network.dot11DefaultCipherAlgorithm.ToString();  
  42.                             targetSSID.securityEnabled = network.securityEnabled;  
  43.                             wifiList.Add(targetSSID);  
  44.                             if (!string.IsNullOrEmpty(conectedNetworkName) && conectedNetworkName.Equals(network.profileName))  
  45.                             {  
  46.                                 targetSSID.connected = true;  
  47.                             }  
  48.                             else  
  49.                             {  
  50.                                 targetSSID.connected = false;  
  51.                             }  
  52.                         }  
  53.                     }  
  54.                 }  
  55.             }  
  56.   
  57.             return wifiList;  
  58.         }  
  59.   
  60. public class WIFISSID  
  61. {  
  62.         public string profileNames;  
  63.         public Wlan.Dot11Ssid SSID;  
  64.         public NativeWifi.Wlan.Dot11AuthAlgorithm dot11DefaultAuthAlgorithm;  
  65.         public string dot11DefaultCipherAlgorithm = "";  
  66.         public bool networkConnectable = true;  
  67.         public string wlanNotConnectableReason = "";  
  68.         public int wlanSignalQuality = 0;  
  69.         public WlanClient.WlanInterface wlanInterface = null;  
  70.         public bool securityEnabled;  
  71.         public bool connected = false;  
  72. }   


寻找当前连接的网络:

[csharp]  view plain  copy
  1. public static string GetCurrentConnection()  
  2.        {  
  3.            WlanClient client = new WlanClient();  
  4.            foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)  
  5.            {  
  6.                Wlan.WlanAvailableNetwork[] networks = wlanIface.GetAvailableNetworkList(0);  
  7.                foreach (Wlan.WlanAvailableNetwork network in networks)  
  8.                {  
  9.                    if (wlanIface.InterfaceState == Wlan.WlanInterfaceState.Connected && wlanIface.CurrentConnection.isState == Wlan.WlanInterfaceState.Connected)  
  10.                    {  
  11.                        return wlanIface.CurrentConnection.profileName;  
  12.                    }  
  13.                }  
  14.            }  
  15.   
  16.            return string.Empty;  
  17.        }  

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

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

[csharp]  view plain  copy
  1. /// <summary>   
  2.        /// 连接到无线网络  
  3.        /// </summary>   
  4.        /// <param name="ssid"></param>   
  5.        public void ConnectToSSID(WIFISSID ssid, string key)   
  6.        {   
  7.            try {  
  8.                String auth = string.Empty;  
  9.                String cipher = string.Empty;   
  10.                bool isNoKey = false;  
  11.                String keytype = string.Empty;   
  12.                switch (ssid.dot11DefaultAuthAlgorithm)   
  13.                {   
  14.                    case Wlan.Dot11AuthAlgorithm.IEEE80211_Open:   
  15.                        auth = "open"break;   
  16.                    //case Wlan.Dot11AuthAlgorithm.IEEE80211_SharedKey:   
  17.                    // 'not implemented yet;   
  18.                    //break;   
  19.                    case Wlan.Dot11AuthAlgorithm.RSNA:   
  20.                        auth = "WPA2PSK"break;   
  21.                    case Wlan.Dot11AuthAlgorithm.RSNA_PSK:   
  22.                        auth = "WPA2PSK"break;   
  23.                    case Wlan.Dot11AuthAlgorithm.WPA:   
  24.                        auth = "WPAPSK"break;   
  25.                    case Wlan.Dot11AuthAlgorithm.WPA_None:   
  26.                        auth = "WPAPSK"break;   
  27.                    case Wlan.Dot11AuthAlgorithm.WPA_PSK:   
  28.                        auth = "WPAPSK"break;   
  29.                }   
  30.                  
  31.                switch (ssid.dot11DefaultCipherAlgorithm)   
  32.                {   
  33.                    case Wlan.Dot11CipherAlgorithm.CCMP:   
  34.                        cipher = "AES";   
  35.                        keytype = "passPhrase";   
  36.                        break;   
  37.                    case Wlan.Dot11CipherAlgorithm.TKIP:   
  38.                        cipher = "TKIP";   
  39.                        keytype = "passPhrase";  
  40.                        break;   
  41.                    case Wlan.Dot11CipherAlgorithm.None:   
  42.                        cipher = "none"; keytype = "";   
  43.                        isNoKey = true;   
  44.                        break;   
  45.                    case Wlan.Dot11CipherAlgorithm.WEP:   
  46.                        cipher = "WEP";   
  47.                        keytype = "networkKey";   
  48.                        break;   
  49.                    case Wlan.Dot11CipherAlgorithm.WEP40:   
  50.                        cipher = "WEP";   
  51.                        keytype = "networkKey";   
  52.                        break;   
  53.                    case Wlan.Dot11CipherAlgorithm.WEP104:  
  54.                        cipher = "WEP";   
  55.                        keytype = "networkKey";   
  56.                        break;  
  57.                }  
  58.   
  59.                if (isNoKey && !string.IsNullOrEmpty(key))  
  60.                {  
  61.                    infoTB.Text = "无法连接网络!";  
  62.                    Loger.WriteLog("无法连接网络",  
  63.                        "SSID:" + this.ssid.SSID + "\r\n"  
  64.                        + "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"  
  65.                        + "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString());  
  66.                    return;  
  67.                }  
  68.                else if (!isNoKey && string.IsNullOrEmpty(key))  
  69.                {  
  70.                    infoTB.Text = "无法连接网络!";  
  71.                    Loger.WriteLog("无法连接网络",  
  72.                        "SSID:" + this.ssid.SSID + "\r\n"  
  73.                        + "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"  
  74.                        + "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString());  
  75.                    return;  
  76.                }  
  77.                else  
  78.                {  
  79.                    string profileName = ssid.profileNames; // this is also the SSID   
  80.                    string mac = StringToHex(profileName);  
  81.                    string profileXml = string.Empty;  
  82.                    if (!string.IsNullOrEmpty(key))  
  83.                    {  
  84.                        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>",  
  85.                            profileName, mac, auth, cipher, keytype, key);   
  86.                    }  
  87.                    else  
  88.                    {  
  89.                        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>",  
  90.                            profileName, mac, auth, cipher, keytype);   
  91.                    }  
  92.   
  93.                    ssid.wlanInterface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, true);  
  94.                    //ssid.wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, ssid.profileNames);  
  95.                    bool success = ssid.wlanInterface.ConnectSynchronously(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName, 15000);  
  96.                    if (!success)  
  97.                    {  
  98.                        infoTB.Text = "连接网络失败!";  
  99.                        Loger.WriteLog("连接网络失败",  
  100.                            "SSID:" + this.ssid.SSID + "\r\n"  
  101.                            + "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"  
  102.                            + "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString() + "\r\n");  
  103.                        return;  
  104.                    }  
  105.                }   
  106.            }   
  107.            catch (Exception e)   
  108.            {  
  109.                infoTB.Text = "无法连接网络!" + e.Message;  
  110.                Loger.WriteLog("无法连接网络",  
  111.                    "SSID:" + this.ssid.SSID + "\r\n"  
  112.                    + "Dot11AuthAlgorithm:" + ssid.dot11DefaultAuthAlgorithm + "\r\n"  
  113.                    + "Dot11CipherAlgorithm:" + ssid.dot11DefaultAuthAlgorithm.ToString() + "\r\n"  
  114.                    + e.Message);  
  115.                return;  
  116.            }   
  117.        }   

如果想要了解连接无线网络过程中的细节,可以注册WlanInterface的WlanConnectionNotification事件。该事件会对当连接的连接状态进行通知,下面是简单的通知事件的实现,根据通知的内容在界面上显示提示信息:
[csharp]  view plain  copy
  1. private void WlanInterface_WlanConnectionNotification(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData)  
  2.        {  
  3.            try  
  4.            {  
  5.                this.Dispatcher.BeginInvoke(new Action(() =>  
  6.                {  
  7.                    if (!this.ssid.profileNames.Equals(connNotifyData.profileName))  // 是否是当前SSID的通知  
  8.                    {  
  9.                        return;  
  10.                    }  
  11.   
  12.                    if (notifyData.notificationSource == Wlan.WlanNotificationSource.ACM)  
  13.                    {  
  14.                          
  15.                        int notificationCode = (int)notifyData.NotificationCode;  
  16.                        switch (notificationCode)  
  17.                        {  
  18.                            case (int)Wlan.WlanNotificationCodeAcm.ConnectionStart:  
  19.                                Loger.WriteLog("开始连接无线网络" + this.ssid.profileNames);  
  20.                                infoTB.Text = "开始连接无线网络......";  
  21.                                break;  
  22.                            case (int)Wlan.WlanNotificationCodeAcm.ConnectionComplete:  
  23.                                Loger.WriteLog("连接无线网络成功" + this.ssid.profileNames);  
  24.                                infoTB.Text = "连接无线网络成功!";  
  25.                                this.DialogResult = true;  
  26.                                break;  
  27.                            case (int)Wlan.WlanNotificationCodeAcm.Disconnecting:  
  28.                                Loger.WriteLog("正在断开无线网络连接" + this.ssid.profileNames);  
  29.                                infoTB.Text = "正在断开无线网络连接......";  
  30.                                break;  
  31.                            case (int)Wlan.WlanNotificationCodeAcm.Disconnected:  
  32.                                Loger.WriteLog("已经断开无线网络连接" + this.ssid.profileNames);  
  33.                                infoTB.Text = "已经断开无线网络连接!";  
  34.                                this.DialogResult = true;  
  35.                                break;  
  36.                        }  
  37.                    }  
  38.                }));  
  39.            }  
  40.            catch (Exception e)  
  41.            {  
  42.                Loger.WriteLog(e.Message);  
  43.            }  
  44.        }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值