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

        // 字符串轉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 = 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;
    }
}


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名稱", 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM