C++ 实现Windows WIFI管理器

文章目录

  • 前言
  • 一、代码
  • 二、补充知识
  • 三、遇到的问题
    • 字符集转换
  • 四、剩余问题
  • 总结


前言

出于项目需要,需要用C++开发一个wifi界面,实现wifi扫描、wifi连接与断开、wifi密码记住的基础功能。


一、代码

话不多说,直接上代码。

#pragma once
#include <wlanapi.h>
#include <vector>
#include <string>
#include <shared_mutex>

#include "Utility/EncodingFormat/EncodingConversion.h"

#pragma comment(lib, "wlanapi.lib")
#pragma comment(lib, "ole32.lib")

/// <summary>
/// brief	Record the wifi info that could be used
/// 
/// author	Canliang Wu
/// Day		2023/12/20
/// </summary>
struct WifiInfo
{
	GUID m_guid;							// GUID(全局唯一标识符)是一个128位的唯一标识符,通常表示为32个十六进制数字的字符串。用于标识无线网络接口。每个接口都有一个唯一的 GUID,它可以用来区分计算机上的不同无线网络接口。
	DOT11_BSS_TYPE m_dot11BssType;			// WiFi网络的基本服务集类型
	DOT11_AUTH_ALGORITHM m_authAlgo;		// 默认的身份验证算法
	DOT11_CIPHER_ALGORITHM m_cipherAlgo;	// 默认的加密算法
	std::wstring m_wifiName;				// Wifi名称(Unicode 编码)
	std::string m_wifiSSID;					// 无线网络的 SSID (OEM 编码页)
	int m_wifiIntensity = 0;				// 信号强度,0 ~ 100
	bool m_wifiConnected = false;			// 目前是否连接
	bool m_bHaveProfile = false;			// 是否存在profile
};

enum class WifiMsg : char
{
	Default = 0,

	ScanComplete,
	ScanFailed,
	ConnectionSuccessful,
	ConnectionFailed,
	DisconnectionSuccessful,
	DisconnectionFailed
};

class WifiManager
{
public:
	WifiManager(){}
	~WifiManager() { CloseWLAN(); }

public:

	/*
	* @brief	Open the WLAN for getting client handle and registering notification
	* @param	hwnd - the parent handle for posting the message
	* @param	msgID - the message ID which parent window wants to receive   	
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool OpenWLAN(HWND hwnd, UINT msgID)
	{
		// 1. Prepare the parent info
		m_parentHwnd = hwnd;
		m_msgID = msgID;

		// 2. Get WLAN client handle
		DWORD dwNegotiatedVersion;
		m_dwResult = WlanOpenHandle(1, nullptr, &dwNegotiatedVersion, &m_clientHandle);
		if (m_dwResult != ERROR_SUCCESS)
		{
			CloseWLAN();
			return false;
		}

		// 3. Register the message notification
		if ((m_dwResult = WlanRegisterNotification(m_clientHandle, WLAN_NOTIFICATION_SOURCE_ALL, TRUE, WLAN_NOTIFICATION_CALLBACK(onNotificationCallback), this, nullptr, nullptr)) != ERROR_SUCCESS)
		{
			CloseWLAN();
			return false;
		}

		// 4. First scanning
		if (!ScanWLAN())
			return false;

		return true;
	}

	/*
	* @brief	Close the WLAN 
	* @param	hwnd - the parent handle for posting the message
	* @param	msgID - the message ID which parent window wants to receive
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool CloseWLAN()
	{
		if (m_clientHandle)
		{
			m_dwResult = WlanCloseHandle(m_clientHandle, nullptr);

			if (m_dwResult == ERROR_SUCCESS)
			{
				m_clientHandle = NULL;

				return true;
			}
			else
			{
				return false;
			}
		}

		return true;
	}

	/*
	* @brief	Just scan the PC card and start scanning the avilable wifi list (We will receive the 'wlan_notification_acm_scan_complete' message in the next four seconds)
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool ScanWLAN()
	{
#pragma region 1. Scan the PC card
		PWLAN_INTERFACE_INFO_LIST pInterfaceList = NULL;
		m_dwResult = WlanEnumInterfaces(m_clientHandle, nullptr, &pInterfaceList);
		if (m_dwResult != ERROR_SUCCESS)
		{
			WlanFreeMemory(pInterfaceList);
			CloseWLAN();
			return false;
		}

		m_vGuid.clear();
		for (unsigned int i = 0; i < (int)pInterfaceList->dwNumberOfItems; i++)
		{
			auto pIfInfo = (WLAN_INTERFACE_INFO*)&pInterfaceList->InterfaceInfo[i];
			m_vGuid.push_back(pIfInfo->InterfaceGuid);
		}

		WlanFreeMemory(pInterfaceList);
#pragma endregion

#pragma region 2. Scan the avilable wifi list for each PC card
		for (auto& guid : m_vGuid)
		{
			m_dwResult = WlanScan(m_clientHandle, &guid, NULL, NULL, NULL);
			if (m_dwResult != ERROR_SUCCESS)
			{
				return false;
			}
		}
#pragma endregion

		return true;
	}

	/*
	* @brief	Connect the wifi without password
	* @param	wifiInfo - current wifi info
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool ConnectWLANWithoutPassword(const WifiInfo& wifiInfo)
	{
		m_curWifiInfo = wifiInfo;

		WLAN_CONNECTION_PARAMETERS wlanConnPara;

		/*wlan_connection_mode_profile			将使用配置文件进行连接。
		wlan_connection_mode_temporary_profile	将使用临时配置文件进行连接。
		wlan_connection_mode_discovery_secure	安全发现将用于建立连接。
		wlan_connection_mode_discovery_unsecure	将使用不安全的发现来建立连接。
		wlan_connection_mode_auto				无线服务使用持久性配置文件自动启动连接。
		wlan_connection_mode_invalid*/
		wlanConnPara.wlanConnectionMode = wlan_connection_mode_profile;
		wlanConnPara.strProfile = wifiInfo.m_wifiName.c_str();
		wlanConnPara.pDot11Ssid = NULL;													//设置为NULL时,会去配置有的ssid
		wlanConnPara.dot11BssType = dot11_BSS_type_infrastructure;						//dot11_BSS_type_any, I do not need it this time.
		wlanConnPara.pDesiredBssidList = NULL;											// the desired BSSID list is empty
		wlanConnPara.dwFlags = WLAN_CONNECTION_HIDDEN_NETWORK;							//it works on my WIN7\8
		
		m_dwResult = WlanConnect(m_clientHandle, &wifiInfo.m_guid, &wlanConnPara, NULL);

		return m_dwResult == ERROR_SUCCESS;
	}

	/*
	* @brief	Connect the wifi with password
	* @param	wifiInfo - current wifi info
	* @param	password - the password
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool ConnectWLANWithPassword(const WifiInfo& wifiInfo, const std::wstring password)
	{
		// 1. Set the profile into system
		if (!setProfile(wifiInfo, password))
			return false;

		// 2. Connect wifi
		if (!ConnectWLANWithoutPassword(wifiInfo))
			return false;

		return true;
	}

	/*
	* @brief	Disconnect the wifi
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool Disconnect(const WifiInfo& wifiInfo)
	{
		m_dwResult = WlanDisconnect(m_clientHandle, &wifiInfo.m_guid, NULL);
		return m_dwResult == ERROR_SUCCESS;
	}

	/*
	* @brief	Called from paranet window to get the wifi info list when it received the 'wlan_notification_acm_scan_complete' message
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	void GetWifiInfoVec(std::vector<WifiInfo>& vWlanInfo) 
	{
		std::shared_lock<std::shared_mutex> lock(m_mutex);
		vWlanInfo = m_vWlanInfo; 
	}

	/*
	* @brief	Get the error info
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	std::string GetError()
	{
		std::string str_error = "Various error codes.";
		switch (m_dwResult)
		{
		case ERROR_SUCCESS:
			str_error = "SUCCESS.";
			break;
		case ERROR_INVALID_PARAMETER:
			str_error = "One of the following conditions occurred:\n"
				"hClientHandle is NULL or invalid.\n"
				"pInterfaceGuid is NULL.\n"
				"pConnectionParameters is NULL.\n"
				"more:https://docs.microsoft.com/zh-cn/windows/win32/api/wlanapi/nf-wlanapi-wlanconnect.";
			break;
		case ERROR_NOT_ENOUGH_MEMORY:
			str_error = "Failed to allocate memory to create the client context.";
			break;
		case ERROR_REMOTE_SESSION_LIMIT_EXCEEDED:
			str_error = "Too many handles have been issued by the server.";
			break;
		case ERROR_INVALID_HANDLE:
			str_error = "The handle hClientHandle was not found in the handle table.";
			break;
		case ERROR_NDIS_DOT11_POWER_STATE_INVALID:
			str_error = "The radio associated with the interface is turned off. There are no available networks when the radio is off.";
			break;
		case ERROR_ACCESS_DENIED:
			str_error = "The caller does not have sufficient permissions.";
			break;
		case ERROR_ALREADY_EXISTS:
			str_error = "strProfileXml specifies a network that already exists.";
			break;
		case ERROR_BAD_PROFILE:
			str_error = "The profile specified by strProfileXml is not valid. If this value is returned, pdwReasonCode specifies the reason the profile is invalid.";
			break;
		case ERROR_NO_MATCH:
			str_error = "The interface does not support one or more of the capabilities specified in the profile.";
			break;
		default:
			str_error = "Various error codes.";
			break;
		}
		return str_error;
	}

private:
	/*
	* @brief	消息回调,获取WLAN连接的各种状态提示
	* @param	data - NotificationSource 字段 对WLAN系统消息进行分类,NotificationCode表示系统消息的具体消息类型
	* @param	context - the param passed from the dialog register this function
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	static void onNotificationCallback(PWLAN_NOTIFICATION_DATA data, PVOID context)
	{
		if (data != NULL && data->NotificationSource == WLAN_NOTIFICATION_SOURCE_ACM)
		{
			WifiManager* pWifiContext = reinterpret_cast<WifiManager*>(context);
			if (!pWifiContext) return;

			switch (data->NotificationCode)
			{
			case wlan_notification_acm_scan_complete:
			{
				pWifiContext->getAvailableNetworkList();
				PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::ScanComplete), 0);
				OutputDebugString(_T("Scan Successful\n"));
				break;
			}
			case wlan_notification_acm_scan_fail:
			{
				DWORD* pScanFailReason = reinterpret_cast<DWORD*>(data->pData);
				OutputDebugString(_T("Scan Failed\n"));
				PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::ScanFailed), 0);
				break;
			}
			case wlan_notification_acm_connection_start: break;
			case wlan_notification_acm_connection_complete:
			{
				pWifiContext->ScanWLAN();
				
				if (pWifiContext->queryConnectionStatus(pWifiContext->m_curWifiInfo.m_guid))
				{
					OutputDebugString(_T("Connection Successful\n"));
					PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::ConnectionSuccessful), 0);
				}
				else
				{
					OutputDebugString(_T("Connection Failed\n"));
					PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::ConnectionFailed), 0);
				}
				break;
			}
			case wlan_notification_acm_connection_attempt_fail:
			{
				//PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::ConnectionFailed), 0);
				OutputDebugString(_T("Connection Attemp Failed\n"));
				break;
			}
			case wlan_notification_acm_disconnecting: break;
			case wlan_notification_acm_disconnected:
			{
				pWifiContext->ScanWLAN();

				if (pWifiContext->queryConnectionStatus(pWifiContext->m_curWifiInfo.m_guid))
				{
					OutputDebugString(_T("Disconnection Failed\n"));
					PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::DisconnectionFailed), 0);
				}
				else
				{
					OutputDebugString(_T("Disconnection Successful\n"));
					PostMessage(pWifiContext->m_parentHwnd, pWifiContext->m_msgID, WPARAM(WifiMsg::DisconnectionSuccessful), 0);
				}

				break;
			}
			default:
				break;
			}
		}
	}

	/*
	* @brief	Get avaliable network list after receiving the 'wlan_notification_acm_scan_complete' message
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool getAvailableNetworkList()
	{
		std::unique_lock<std::shared_mutex> lock(m_mutex);
		m_vWlanInfo.clear();

		for (auto& guid : m_vGuid)
		{
			PWLAN_AVAILABLE_NETWORK_LIST pWLAN_AVAILABLE_NETWORK_LIST = nullptr;
			m_dwResult = WlanGetAvailableNetworkList(m_clientHandle, &guid, 2, nullptr, &pWLAN_AVAILABLE_NETWORK_LIST);
			if (m_dwResult != ERROR_SUCCESS)
			{
				WlanFreeMemory(pWLAN_AVAILABLE_NETWORK_LIST);
				CloseWLAN();

				return false;
			}

			for (DWORD i = 0; i < pWLAN_AVAILABLE_NETWORK_LIST->dwNumberOfItems; i++)
			{
				WLAN_AVAILABLE_NETWORK& network = pWLAN_AVAILABLE_NETWORK_LIST->Network[i];

				if (network.dot11Ssid.uSSIDLength != 0 )
				{
					std::string str_ssid((char*)network.dot11Ssid.ucSSID);

					WifiInfo info;
					info.m_guid = guid;
					info.m_wifiSSID = str_ssid;
					info.m_wifiName = EncodingConversion::UTF8ToUnicode(str_ssid);
					info.m_wifiIntensity = (int)network.wlanSignalQuality;
					info.m_wifiConnected = network.dwFlags & WLAN_AVAILABLE_NETWORK_CONNECTED;
					info.m_bHaveProfile = network.dwFlags & WLAN_AVAILABLE_NETWORK_HAS_PROFILE;
					info.m_dot11BssType = network.dot11BssType;
					info.m_authAlgo = network.dot11DefaultAuthAlgorithm;
					info.m_cipherAlgo = network.dot11DefaultCipherAlgorithm;

					// To fix the problem that have two same SSID when this wifi have profile temporarily(Canliang Wu, 2023/12/20)
					std::wstring targetWifiName = info.m_wifiName;
					auto it = std::find_if(m_vWlanInfo.begin(), m_vWlanInfo.end(), [targetWifiName](const WifiInfo& wifi) {
						return wifi.m_wifiName == targetWifiName;
					});

					if (it == m_vWlanInfo.end())
					{
						m_vWlanInfo.push_back(info);
					}
					else
					{
						if (!it->m_bHaveProfile && info.m_bHaveProfile)
						{
							m_vWlanInfo.erase(it);
							m_vWlanInfo.push_back(info);
						}
					}

				}
			}

			WlanFreeMemory(pWLAN_AVAILABLE_NETWORK_LIST);

			CString guidStr = guidToWstring(guid).c_str();
			CString sizeStr;
			sizeStr.Format(L"size = %d\n", m_vWlanInfo.size());
			OutputDebugString(guidStr + _T(", ") + sizeStr);
		}

		return true;
	}

	/*
	* @brief	Convert to guid into wstring
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	std::wstring guidToWstring(const GUID& guid) {
		WCHAR buffer[39];
		swprintf(buffer, L"%08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X",
			guid.Data1, guid.Data2, guid.Data3,
			guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3],
			guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
		return buffer;
	}

	/*
	* @brief	Set the new wifi profile into system
	* @param	wifiInfo - wifi info
	* @param	password - the password   	
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	bool setProfile(const WifiInfo& wifiInfo, const std::wstring& password)
	{
		auto connectInfoSize = sizeof(WLAN_CONNECTION_ATTRIBUTES);
		auto opCode = wlan_opcode_value_type_invalid;

		auto STR_NAME = L"WIFINAME";
		auto STR_SSID = L"WIFISSID";
		auto STR_PASSWORD = L"PASSWORD";
		auto STR_CONNECTIONTYPE = L"CONNECTIONTYPE";
		auto STR_AUTHENTICATION = L"AUTHENTICATION";
		auto STR_ENCRYPTION = L"ENCRYPTION";

		auto STR_PROFILE_DEMO =
		L"<?xml version=\"1.0\"?> \
		<WLANProfile xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v1\">\
			<name>WIFINAME</name>\
			<SSIDConfig>\
				<SSID>\
					<name>WIFISSID</name>\
				</SSID>\
			</SSIDConfig>\
			<connectionType>CONNECTIONTYPE</connectionType>\
			<connectionMode>auto</connectionMode>\
			<MSM>\
				<security>\
					<authEncryption>\
						<authentication>AUTHENTICATION</authentication>\
						<encryption>ENCRYPTION</encryption>\
						<useOneX>false</useOneX>\
					</authEncryption>\
					<sharedKey>\
						<keyType>passPhrase</keyType>\
						<protected>false</protected>\
						<keyMaterial>PASSWORD</keyMaterial>\
					</sharedKey>\
				</security>\
			</MSM>\
		</WLANProfile>";

		std::wstring strProfile = STR_PROFILE_DEMO;
		stringReplace(strProfile, STR_NAME, wifiInfo.m_wifiName);
		stringReplace(strProfile, STR_SSID, stringToWideChar(wifiInfo.m_wifiSSID));
		stringReplace(strProfile, STR_PASSWORD, password);
		
		switch (wifiInfo.m_dot11BssType)
		{
		case dot11_BSS_type_infrastructure:
			stringReplace(strProfile, STR_CONNECTIONTYPE, L"ESS");
			break;
		case dot11_BSS_type_independent:
			stringReplace(strProfile, STR_CONNECTIONTYPE, L"IBSS");
			break;
		case dot11_BSS_type_any:
			stringReplace(strProfile, STR_CONNECTIONTYPE, L"ANY");
			break;
		default:
			OutputDebugString(L"Unknown BSS Type");
			return false;
		}

		switch (wifiInfo.m_authAlgo)
		{
		case DOT11_AUTH_ALGO_80211_OPEN:
			stringReplace(strProfile, STR_AUTHENTICATION, L"open");
			OutputDebugString(L"Open 802.11 authentication\n");
			break;
		case DOT11_AUTH_ALGO_80211_SHARED_KEY:
			stringReplace(strProfile, STR_AUTHENTICATION, L"shared");
			OutputDebugString(L"Shared 802.11 authentication");
			break;
		case DOT11_AUTH_ALGO_WPA:
			stringReplace(strProfile, STR_AUTHENTICATION, L"WPA");
			OutputDebugString(L"WPA-Enterprise 802.11 authentication\n");
			break;
		case DOT11_AUTH_ALGO_WPA_PSK:
			stringReplace(strProfile, STR_AUTHENTICATION, L"WPAPSK");
			OutputDebugString(L"WPA-Personal 802.11 authentication\n");
			break;
		case DOT11_AUTH_ALGO_WPA_NONE:
			stringReplace(strProfile, STR_AUTHENTICATION, L"none");
			OutputDebugString(L"WPA-NONE,not exist in MSDN\n");
			break;
		case DOT11_AUTH_ALGO_RSNA:
			stringReplace(strProfile, STR_AUTHENTICATION, L"WPA2");
			OutputDebugString(L"WPA2-Enterprise 802.11 authentication\n");
			break;
		case DOT11_AUTH_ALGO_RSNA_PSK:
			stringReplace(strProfile, STR_AUTHENTICATION, L"WPA2PSK");
			OutputDebugString(L"WPA2-Personal 802.11 authentication\n");
			break;
		case DOT11_AUTH_ALGO_WPA3:
			stringReplace(strProfile, STR_AUTHENTICATION, L"WPA3");
			break;
		case DOT11_AUTH_ALGO_WPA3_SAE:
			stringReplace(strProfile, STR_AUTHENTICATION, L"WPA3SAE");
			break;
		default:
			OutputDebugString(L"Unknown authentication");
			return false;
		}

		switch (wifiInfo.m_cipherAlgo)
		{
		case DOT11_CIPHER_ALGO_NONE:
			stringReplace(strProfile, STR_ENCRYPTION, L"none");
			break;
		case DOT11_CIPHER_ALGO_WEP40:
			stringReplace(strProfile, STR_ENCRYPTION, L"WEP");
			break;
		case DOT11_CIPHER_ALGO_TKIP:
			stringReplace(strProfile, STR_ENCRYPTION, L"TKIP");
			break;
		case DOT11_CIPHER_ALGO_CCMP:
			stringReplace(strProfile, STR_ENCRYPTION, L"AES");
			break;
		case DOT11_CIPHER_ALGO_WEP104:
			stringReplace(strProfile, STR_ENCRYPTION, L"WEP");
			break;
		case DOT11_CIPHER_ALGO_WEP:
			stringReplace(strProfile, STR_ENCRYPTION, L"WEP");
			break;
		case DOT11_CIPHER_ALGO_WPA_USE_GROUP:
			OutputDebugString(L"USE-GROUP not exist in MSDN");
			break;
		default:
			OutputDebugString(L"Unknown encryption");
			return false;
		}

		WLAN_REASON_CODE Wlanreason;
		m_dwResult = WlanSetProfile(m_clientHandle, &wifiInfo.m_guid, 0, strProfile.c_str(), NULL, true, NULL, &Wlanreason);

		return m_dwResult == ERROR_SUCCESS;
	}

	/*
	* @brief	Replace specified characters in the string
	* @param	inputoutopt - the whole string 
	* @param	oldStr - the characters in inputoutopt to be replaced
	* @param	newStr - the characters for replacing
	*
	* @author 	Canliang Wu
	* @day		2023/12/19
	*/
	void stringReplace(std::wstring& inputoutopt, const std::wstring oldStr, const std::wstring newStr)
	{
		std::wstring::size_type pos = 0;
		std::wstring::size_type a = oldStr.size();
		std::wstring::size_type b = newStr.size();
		while ((pos = inputoutopt.find(oldStr, pos)) != std::string::npos)
		{
			inputoutopt.replace(pos, a, newStr);
			pos += b;
		}
	}

	/*
	* @brief	Query the wifi connection state after receive the 'wlan_notification_acm_connection_complete ' message
	* @param	interfaceGuid - guid
	*
	* @author 	Canliang Wu
	* @day		2023/12/20
	*/
	bool queryConnectionStatus(const GUID& interfaceGuid) 
	{
		PWLAN_CONNECTION_ATTRIBUTES pConnectInfo = NULL;
		DWORD connectInfoSize;
		WLAN_OPCODE_VALUE_TYPE opCode;

		m_dwResult = WlanQueryInterface(m_clientHandle, &interfaceGuid, wlan_intf_opcode_current_connection, nullptr, &connectInfoSize, (PVOID*)&pConnectInfo, &opCode);

		bool bConnected = false;
		if (m_dwResult == ERROR_SUCCESS) 
		{
			if (pConnectInfo->isState == wlan_interface_state_connected) 
			{
				bConnected = true;
			}
		}
		
		if (pConnectInfo)
		{
			WlanFreeMemory(pConnectInfo);
		}
	
		return bConnected;
	}

	/*
	* @brief	Convert the multi byte string to wide byte string
	* @note   	CP_OEMCP means keeping the string same code page with the system
	*
	* @author 	Canliang Wu
	* @day		2023/12/21
	*/
	std::wstring stringToWideChar(const std::string pKey)
	{
		char* pCStrKey = const_cast<char*>(pKey.c_str());
		//第一次调用返回转换后的字符串长度,用于确认为wchar_t*开辟多大的内存空间
		int pSize = MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, NULL, 0);
		wchar_t* pWCStrKey = new wchar_t[pSize];
		//第二次调用将单字节字符串转换成双字节字符串
		MultiByteToWideChar(CP_OEMCP, 0, pCStrKey, strlen(pCStrKey) + 1, pWCStrKey, pSize);

		std::wstring res(pWCStrKey);
		
		delete[] pWCStrKey;
		pWCStrKey = nullptr;

		return res;
	}

private:
	/// Client handle
	HANDLE m_clientHandle = NULL;

	/// Error code
	DWORD m_dwResult = 0;

	/// GUID vector
	std::vector<GUID> m_vGuid;

	/// Mutex for locking m_vWlanInfo
	std::shared_mutex m_mutex;

	/// Wifi info vector
	std::vector<WifiInfo> m_vWlanInfo;

	/// Current wifi info
	WifiInfo m_curWifiInfo;

	/// Post message 
	HWND m_parentHwnd;
	UINT m_msgID;
};

二、补充知识

  1. 对于未连接过的wifi,系统的做法是,先写入配置文件,然后再根据配置文件去连接。这也是我代码中的做法。
  2. 配置文件路径在:C:\ProgramData\Microsoft\Wlansvc\Profiles\Interfaces\{网卡GUID}\{Wifi GUID}.xml,再通过Notepad++打开可以看到明文信息。
  3. 通过管理员权限打开cmd,输入下面命令可以查看相关信息。
netsh wlan show profile							// 列出所有的wifi profile
netsh wlan delete profile name="xxx"			// 删除wifi名=xxx的profile
netsh wlan show profile name="xxx" key=clear	// 显示wifi名=xxx的profile详细信息

三、遇到的问题

字符集转换

  1. 我们通过std::string str_ssid((char*)network.dot11Ssid.ucSSID)得到wifi名称,但此时是多字节字符串,项目需要的是宽字节字符串,所以通过EncodingConversion::UTF8ToUnicode(str_ssid)转换为Unicode编码。
  2. 重新写到配置文件中,因为系统API需要的是宽字节字符串,但是如果直接使用wifiInfo.m_wifiSSID是错误的。因为它现在虽然是宽字节,但是却是Unicode字符集。而系统API需要的字符集则不确定,所以使用CP_OEMCP将从系统出来的ssid转回系统需要的宽字节字符串。(说实话,这里我也不太理解,有更懂的小伙伴欢迎留言区评论!)

四、剩余问题

目前代码还剩下这些问题:

  1. Wifi连接时间要比直接通过系统连接来的长;
  2. 存在wifi名全为空白的现象(但是SSID len肯定不为0,因为上面有筛选。但是由于无法稳定找到那个空白wifi,所以也没去调试);
  3. 对于iphone手机热点,需要开启“最大兼容性”才可以连接成功,安卓手机则不需要。
  4. Wifi的总开关仍在系统,也就是需要桌面右下角开启WLAN才可以扫描wifi等操作。
    在这里插入图片描述

总结

总之,我还是希望有人能够在我的基础上,修改存在的问题,并通知我!感谢!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/288792.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

迎接数字化,亿发专业MES制造管理解决方案,助力湖南企业智能制造管理

在20世纪80年代末&#xff0c;美国先进制造研究机构&#xff08;AMT&#xff09;率先提出了MES&#xff08;Manufacturing Execution System&#xff09;的概念&#xff0c;即制造执行系统或生产实施系统。面向车间的生产过程管理与实时信息管理&#xff0c;解决车间生产任务的…

EasyExcel解决导出字符串变成数字问题

&#x1f341; 作者&#xff1a;知识浅谈&#xff0c;CSDN博客专家&#xff0c;阿里云签约博主&#xff0c;InfoQ签约博主&#xff0c;华为云云享专家&#xff0c;51CTO明日之星 &#x1f4cc; 擅长领域&#xff1a;全栈工程师、爬虫、ACM算法 &#x1f492; 公众号&#xff1a…

CMake入门教程【基础篇】在Windows、Linux上安装CMake

&#x1f608;「CSDN主页」&#xff1a;传送门 &#x1f608;「Bilibil首页」&#xff1a;传送门 &#x1f608;「本文的内容」&#xff1a;CMake入门教程 &#x1f608;「动动你的小手」&#xff1a;点赞&#x1f44d;收藏⭐️评论&#x1f4dd; 文章目录 1.windows平台第1步&…

市场复盘总结 20240103

仅用于记录当天的市场情况,用于统计交易策略的适用情况,以便程序回测 短线核心:不参与任何级别的调整 昨日回顾: 方法一:指标选股 select * from dbo.ResultAll where 入选类型 like %指标选股% and 入选日期=20240103;方法二:趋势选股法 1、最低价持续3日上涨 2、均价…

c 编码(进行中)

编码出来的jpeg图片只有红&#xff0c;绿色。排查中 ​​​​​​​ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> #in…

jar包反编译

tips&#xff1a;下载地址在评论区 一、解压出来单击.exe文件 二、 将jar包拖到灰色区域 如图所示 三、保存 1.File->Save All Sourses->解压缩 2.快捷键CtrlAltS

C++面向对象语法总结(一)

一、类 C中可以使用struct、class两个关键字来定义一个类struct和class的区别 struct的默认成员权限是publicclass的默认成员权限是private实际开发中&#xff0c;用class表示类的比较多&#xff0c;因为涉及到封装的思想 在函数中创建的对象&#xff0c;都是在栈空间&#xf…

引导过程与服务控制

一、开机启动的完整过程 bios加电自检测-------mbr------grub----------加载内核文件------------启动第一个进程 简述&#xff1a;加电后bios程序会自检硬件&#xff0c;硬件无故障&#xff0c;会根据第一启动项去找内核&#xff0c;一般来说&#xff0c;第一启动项是硬盘&a…

(学习打卡2)重学Java设计模式之六大设计原则

前言&#xff1a;听说有本很牛的关于Java设计模式的书——重学Java设计模式&#xff0c;然后买了(*^▽^*) 开始跟着小傅哥学Java设计模式吧&#xff0c;本文主要记录笔者的学习笔记和心得。 打卡&#xff01;打卡&#xff01; 六大设计原则 &#xff08;引读&#xff1a;这里…

最新-mybatis-plus 3.5分页插件配置

mybatis-plus 3.5分页插件配置 前提 1.项目不是springboot, 是以前的常规spring项目 2.mp 从3.2升级到3.5&#xff0c;升级后发现原本的分页竟然不起作用了&#xff0c;每次查询都是查出所有 前后配置对比 jar包对比 jsqlparser我这里单独引了包&#xff0c;因为版本太低…

[蓝桥杯2020国赛]答疑

答疑 题目描述 有 n 位同学同时找老师答疑。每位同学都预先估计了自己答疑的时间。 老师可以安排答疑的顺序&#xff0c;同学们要依次进入老师办公室答疑。 一位同学答疑的过程如下&#xff1a; 首先进入办公室&#xff0c;编号为 i 的同学需要 si​ 毫秒的时间。然后同学问…

深入理解SPi通讯协议

目录 SPI简介&#xff1a; 主设备通过选择线&#xff08;SS&#xff09; 主设备通过时钟线&#xff08;SCLK&#xff09; 主设备通过主输出线&#xff08;MOSI&#xff09; 主设备通过主输出线&#xff08;MISO&#xff09; SPI读写数据&#xff1a; SPI写入数据&#xf…

超详细解释奇异值分解(SVD)【附例题和分析】

目录 一. 矩阵对角化 二. 奇异值分解 三. 对比奇异值分解与特征值分解 四. SVD分解与四大基础子空间 五. SVD分解的正交矩阵 六. 方阵与SVD分解 七. 单位特征向量与SVD分解 八. 例题分析&#xff1a;秩为1 九. 例题分析&#xff1a;秩为2 十. 计算机网络与矩阵的秩 一…

从董宇辉小作文风波,我们普通人能学到些什么?

哈喽&#xff0c;大家好啊&#xff0c;我是雷工&#xff01; 最近董宇辉小作文风波动静太大了&#xff0c;哪哪都是。 打开公号上都在写董宇辉&#xff0c;打开某音&#xff0c;都在说董宇辉。 这种事其实本来就是立场不同&#xff0c;各个角度来说都有道理的事。 神仙打架&am…

利用深度学习图像识别技术实现教室人数识别

引言 在现代教育环境中&#xff0c;高效管理和监控教室成为了一个重要议题。随着人工智能技术的迅猛发展&#xff0c;特别是深度学习和图像识别领域的突破&#xff0c;我们现在可以通过智能系统来自动识别教室内的人数&#xff0c;从而实现更加智能化的教室管理。 深度学习与图…

手把手教你开发盲盒小程序

在这个数字时代&#xff0c;微信小程序已经成为了各大品牌和个人的主要营销渠道。而盲盒小程序&#xff0c;作为小程序领域中的一种独特类型&#xff0c;更是具有巨大的市场潜力。那么&#xff0c;如何创建和运营一个成功的微信盲盒小程序呢&#xff1f;以下是一份保姆级的教程…

SpringBoot之多环境开发配置

1 多环境开发配置 问题导入 在实际开发中&#xff0c;项目的开发环境、测试环境、生产环境的配置信息是否会一致&#xff1f;如何快速切换&#xff1f; 1.1 多环境启动配置 yaml文件多环境启动 不同环境使用—隔开 示例代码&#xff1a; spring:profiles:active: dev#生产…

Intellij IDEA 快速开发参考

快捷键 核心快捷键 IntelliJ IDEA 作为一个以快捷键为中心的 IDE&#xff0c;为大多数操作建议了键盘快捷键。在这个主题中&#xff0c;您可以找到最不可缺少的列表&#xff0c;使 IntelliJ IDEA 轻松实现第一步。 核心快捷键表&#xff1a; 操作快捷键根据名称查找操作CtrlSh…

阶段十-分布式-Redis02

第一章 Redis 事务 1.1 节 数据库事务复习 数据库事务的四大特性 A&#xff1a;Atomic &#xff0c;原子性&#xff0c;将所以SQL作为原子工作单元执行&#xff0c;要么全部执行&#xff0c;要么全部不执行&#xff1b;C&#xff1a;Consistent&#xff0c;一致性&#xff0…

Django 分页(表单)

目录 一、手动分页二、分页器分页 一、手动分页 1、概念 页码&#xff1a;很容易理解&#xff0c;就是一本书的页码每页数量&#xff1a;就是一本书中某一页中的内容&#xff08;数据量&#xff0c;比如第二页有15行内容&#xff09;&#xff0c;这 15 就是该页的数据量 每一…