wlanapi连接一个已经连接过的wifi
时间: 2023-07-02 20:18:40 浏览: 361
可以使用如下代码连接一个已经连接过的 WiFi 网络:
```c++
#include <windows.h>
#include <wlanapi.h>
#include <wtypes.h>
#include <winerror.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#pragma comment(lib, "wlanapi.lib")
DWORD WlanConnect(LPCWSTR profileName)
{
HANDLE hClient = NULL;
DWORD dwMaxClient = 2;
DWORD dwCurVersion = 0;
DWORD dwResult = 0;
DWORD dwRetVal = 0;
WCHAR GuidString[39] = { 0 };
DWORD dwReasonCode = 0;
PWLAN_INTERFACE_INFO_LIST pIfList = NULL;
PWLAN_INTERFACE_INFO pIfInfo = NULL;
PWLAN_AVAILABLE_NETWORK_LIST pAvailableNetworkList = NULL;
PWLAN_AVAILABLE_NETWORK pAvailableNetwork = NULL;
dwResult = WlanOpenHandle(dwMaxClient, NULL, &dwCurVersion, &hClient);
if (dwResult != ERROR_SUCCESS) {
wprintf(L"WlanOpenHandle failed with error: %u\n", dwResult);
return dwResult;
}
dwResult = WlanEnumInterfaces(hClient, NULL, &pIfList);
if (dwResult != ERROR_SUCCESS) {
wprintf(L"WlanEnumInterfaces failed with error: %u\n", dwResult);
return dwResult;
}
for (DWORD i = 0; i < pIfList->dwNumberOfItems; i++) {
pIfInfo = (WLAN_INTERFACE_INFO *)&pIfList->InterfaceInfo[i];
dwResult = WlanGetAvailableNetworkList(hClient, &pIfInfo->InterfaceGuid, 0, NULL, &pAvailableNetworkList);
if (dwResult != ERROR_SUCCESS) {
wprintf(L"WlanGetAvailableNetworkList failed with error: %u\n", dwResult);
return dwResult;
}
for (DWORD j = 0; j < pAvailableNetworkList->dwNumberOfItems; j++) {
pAvailableNetwork = (WLAN_AVAILABLE_NETWORK *)&pAvailableNetworkList->Network[j];
if (wcscmp(pAvailableNetwork->strProfileName, profileName) == 0) {
WLAN_CONNECTION_PARAMETERS connectionParams;
memset(&connectionParams, 0, sizeof(WLAN_CONNECTION_PARAMETERS));
connectionParams.wlanConnectionMode = wlan_connection_mode_profile;
connectionParams.strProfile = pAvailableNetwork->strProfileName;
connectionParams.pDot11Ssid = NULL;
connectionParams.pDesiredBssidList = NULL;
connectionParams.dot11BssType = dot11_BSS_type_infrastructure;
connectionParams.dwFlags = 0;
dwResult = WlanConnect(hClient, &pIfInfo->InterfaceGuid, &connectionParams, NULL);
if (dwResult != ERROR_SUCCESS) {
wprintf(L"WlanConnect failed with error: %u\n", dwResult);
return dwResult;
}
else {
wprintf(L"Connected to network: %s\n", pAvailableNetwork->strProfileName);
break;
}
}
}
if (pAvailableNetworkList != NULL) {
WlanFreeMemory(pAvailableNetworkList);
pAvailableNetworkList = NULL;
}
}
if (pIfList != NULL) {
WlanFreeMemory(pIfList);
pIfList = NULL;
}
return ERROR_SUCCESS;
}
int wmain(int argc, WCHAR *argv[])
{
DWORD dwResult = 0;
dwResult = WlanConnect(L"Your_WiFi_Profile_Name");
if (dwResult != ERROR_SUCCESS) {
wprintf(L"Failed to connect to WiFi network.\n");
}
return 0;
}
```
其中,`profileName` 参数表示需要连接的 WiFi 网络的配置文件名称,需要修改为你自己的 WiFi 网络配置文件名称。
阅读全文