Elysia Tools
Navigation mobile
C++
Exemples de Fonctionnalités Mobiles Windows C++
Fonctionnalités spécifiques mobiles Windows C++ y compris les informations sur l'appareil, le statut du réseau et la vibration
Exemples
Entrées de cette collection
Informations sur l'Appareil
Obtenir des informations sur l'appareil notamment le modèle, la version du système, les détails du matériel et les capacités
Difficulté
6/10
Temps estimé
25 min
Étiquettes
cpp, mobile, device info, windows
Prérequis
Intermediate C++, Windows API, WMI
// Windows C++ Device Information Examples
// Using Windows API to get system and hardware information
#include <iostream>
#include <string>
#include <windows.h>
#include <sysinfoapi.h>
#include <Lmcons.h>
#include <wbemidl.h>
#include <comdef.h>
#include <wrl/client.h>
#pragma comment(lib, "wbemuuid.lib")
using Microsoft::WRL::ComPtr;
// 1. Basic System Information
class SystemInfo {
public:
static std::string getComputerName() {
CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = sizeof(computerName);
if (GetComputerNameA(computerName, &size)) {
return std::string(computerName);
}
return "Unknown";
}
static std::string getUserName() {
CHAR userName[UNLEN + 1];
DWORD size = sizeof(userName);
if (GetUserNameA(userName, &size)) {
return std::string(userName);
}
return "Unknown";
}
static std::string getWindowsVersion() {
OSVERSIONINFOEXA osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEXA));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXA);
#pragma warning(push)
#pragma warning(disable: 4996)
if (GetVersionExA(reinterpret_cast<LPOSVERSIONINFOA>(&osvi))) {
char version[128];
sprintf_s(version, "Windows %d.%d (Build %d)",
osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
return std::string(version);
}
#pragma warning(pop)
return "Unknown Version";
}
static std::string getSystemDirectory() {
CHAR systemDir[MAX_PATH];
if (GetSystemDirectoryA(systemDir, MAX_PATH)) {
return std::string(systemDir);
}
return "";
}
static std::string getWindowsDirectory() {
CHAR windowsDir[MAX_PATH];
if (GetWindowsDirectoryA(windowsDir, MAX_PATH)) {
return std::string(windowsDir);
}
return "";
}
};
// 2. Memory Information
class MemoryInfo {
public:
struct MemoryStatus {
DWORDLONG totalPhysical;
DWORDLONG availablePhysical;
DWORDLONG totalPageFile;
DWORDLONG availablePageFile;
DWORDLONG totalVirtual;
DWORDLONG availableVirtual;
DWORD memoryLoad;
};
static MemoryStatus getMemoryStatus() {
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
if (GlobalMemoryStatusEx(&status)) {
MemoryStatus result;
result.totalPhysical = status.ullTotalPhys;
result.availablePhysical = status.ullAvailPhys;
result.totalPageFile = status.ullTotalPageFile;
result.availablePageFile = status.ullAvailPageFile;
result.totalVirtual = status.ullTotalVirtual;
result.availableVirtual = status.ullAvailVirtual;
result.memoryLoad = status.dwMemoryLoad;
return result;
}
return MemoryStatus();
}
static std::string formatBytes(DWORDLONG bytes) {
const char* units[] = {"B", "KB", "MB", "GB", "TB"};
int unitIndex = 0;
double size = static_cast<double>(bytes);
while (size >= 1024.0 && unitIndex < 4) {
size /= 1024.0;
unitIndex++;
}
char buffer[64];
sprintf_s(buffer, "%.2f %s", size, units[unitIndex]);
return std::string(buffer);
}
static void displayMemoryInfo() {
MemoryStatus status = getMemoryStatus();
std::cout << "=== Memory Information ===" << std::endl;
std::cout << "Total Physical: " << formatBytes(status.totalPhysical) << std::endl;
std::cout << "Available Physical: " << formatBytes(status.availablePhysical) << std::endl;
std::cout << "Total Page File: " << formatBytes(status.totalPageFile) << std::endl;
std::cout << "Available Page File: " << formatBytes(status.availablePageFile) << std::endl;
std::cout << "Total Virtual: " << formatBytes(status.totalVirtual) << std::endl;
std::cout << "Available Virtual: " << formatBytes(status.availableVirtual) << std::endl;
std::cout << "Memory Load: " << status.memoryLoad << "%" << std::endl;
}
};
// 3. CPU Information
class CPUInfo {
public:
static std::string getProcessorName() {
// Use WMI to get processor name
std::string processorName = "Unknown Processor";
HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr)) {
ComPtr<IWbemLocator> pLoc;
hr = CoCreateInstance(
CLSID_WbemLocator,
nullptr,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
reinterpret_cast<void**>(pLoc.GetAddressOf())
);
if (SUCCEEDED(hr)) {
ComPtr<IWbemServices> pSvc;
hr = pLoc->ConnectServer(
_bstr_t(L"ROOT\CIMV2"),
nullptr,
nullptr,
0,
0,
0,
0,
pSvc.GetAddressOf()
);
if (SUCCEEDED(hr)) {
hr = CoSetProxyBlanket(
pSvc.Get(),
RPC_C_AUTHN_WINNT,
RPC_C_AUTHZ_NONE,
nullptr,
RPC_C_AUTHN_LEVEL_CALL,
RPC_C_IMP_LEVEL_IMPERSONATE,
nullptr,
EOAC_NONE
);
if (SUCCEEDED(hr)) {
ComPtr<IEnumWbemClassObject> pEnumerator;
hr = pSvc->ExecQuery(
_bstr_t(L"WQL"),
_bstr_t(L"SELECT Name FROM Win32_Processor"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
nullptr,
pEnumerator.GetAddressOf()
);
if (SUCCEEDED(hr)) {
IWbemClassObject* pclsObj = nullptr;
ULONG uReturn = 0;
while (pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn) == S_OK) {
VARIANT vtProp;
VariantInit(&vtProp);
hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
if (SUCCEEDED(hr)) {
processorName = _com_util::ConvertBSTRToString(vtProp.bstrVal);
VariantClear(&vtProp);
}
pclsObj->Release();
}
}
}
}
}
CoUninitialize();
}
return processorName;
}
static int getNumberOfCores() {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
return sysInfo.dwNumberOfProcessors;
}
static std::string getProcessorArchitecture() {
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
switch (sysInfo.wProcessorArchitecture) {
case PROCESSOR_ARCHITECTURE_AMD64:
return "x64 (AMD or Intel)";
case PROCESSOR_ARCHITECTURE_ARM:
return "ARM";
case PROCESSOR_ARCHITECTURE_ARM64:
return "ARM64";
case PROCESSOR_ARCHITECTURE_IA64:
return "Intel Itanium";
case PROCESSOR_ARCHITECTURE_INTEL:
return "x86";
default:
return "Unknown Architecture";
}
}
static void displayCPUInfo() {
std::cout << "=== CPU Information ===" << std::endl;
std::cout << "Processor: " << getProcessorName() << std::endl;
std::cout << "Architecture: " << getProcessorArchitecture() << std::endl;
std::cout << "Number of Cores: " << getNumberOfCores() << std::endl;
}
};
// 4. Battery Information
class BatteryInfo {
public:
enum class BatteryStatus {
Unknown,
Discharging,
Charging,
Critical
};
struct BatteryInfoData {
BOOL batteryPresent;
DWORD batteryLifePercent;
BOOL acOnline;
BatteryStatus status;
};
static BatteryInfoData getBatteryInfo() {
BatteryInfoData info;
SYSTEM_POWER_STATUS powerStatus;
if (GetSystemPowerStatus(&powerStatus)) {
info.batteryPresent = powerStatus.BatteryFlag != BATTERY_FLAG_NO_BATTERY;
info.batteryLifePercent = powerStatus.BatteryLifePercent;
info.acOnline = powerStatus.ACLineStatus == AC_LINE_ONLINE;
if (powerStatus.BatteryFlag & BATTERY_FLAG_CRITICAL) {
info.status = BatteryStatus::Critical;
} else if (powerStatus.ACLineStatus == AC_LINE_ONLINE) {
info.status = BatteryStatus::Charging;
} else if (powerStatus.BatteryFlag & BATTERY_FLAG_HIGH ||
powerStatus.BatteryFlag & BATTERY_FLAG_LOW) {
info.status = BatteryStatus::Discharging;
} else {
info.status = BatteryStatus::Unknown;
}
} else {
info.batteryPresent = FALSE;
info.batteryLifePercent = 0;
info.acOnline = FALSE;
info.status = BatteryStatus::Unknown;
}
return info;
}
static std::string getStatusString(BatteryStatus status) {
switch (status) {
case BatteryStatus::Discharging: return "Discharging";
case BatteryStatus::Charging: return "Charging";
case BatteryStatus::Critical: return "Critical";
default: return "Unknown";
}
}
static void displayBatteryInfo() {
BatteryInfoData info = getBatteryInfo();
std::cout << "=== Battery Information ===" << std::endl;
if (info.batteryPresent) {
std::cout << "Battery: Present" << std::endl;
std::cout << "Charge: " << info.batteryLifePercent << "%" << std::endl;
std::cout << "AC Power: " << (info.acOnline ? "Connected" : "Disconnected") << std::endl;
std::cout << "Status: " << getStatusString(info.status) << std::endl;
} else {
std::cout << "Battery: Not present (Desktop system)" << std::endl;
std::cout << "AC Power: " << (info.acOnline ? "Connected" : "Disconnected") << std::endl;
}
}
};
// 5. Display Information
class DisplayInfo {
public:
static void getDisplayInfo() {
HDC hdc = GetDC(nullptr);
int horizontalDPI = GetDeviceCaps(hdc, LOGPIXELSX);
int verticalDPI = GetDeviceCaps(hdc, LOGPIXELSY);
int width = GetDeviceCaps(hdc, HORZRES);
int height = GetDeviceCaps(hdc, VERTRES);
int colorDepth = GetDeviceCaps(hdc, BITSPIXEL);
ReleaseDC(nullptr, hdc);
std::cout << "=== Display Information ===" << std::endl;
std::cout << "Resolution: " << width << " x " << height << std::endl;
std::cout << "DPI: " << horizontalDPI << " x " << verticalDPI << std::endl;
std::cout << "Color Depth: " << colorDepth << " bits" << std::endl;
}
static bool isHighDPI() {
HDC hdc = GetDC(nullptr);
int dpi = GetDeviceCaps(hdc, LOGPIXELSX);
ReleaseDC(nullptr, hdc);
return dpi >= 120;
}
};
// 6. Disk Information
class DiskInfo {
public:
static void getDiskInfo(const std::string& drive = "C:\\") {
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalBytes;
ULARGE_INTEGER totalFreeBytes;
if (GetDiskFreeSpaceExA(
drive.c_str(),
&freeBytesAvailable,
&totalBytes,
&totalFreeBytes)) {
std::cout << "=== Disk Information (" << drive << ") ===" << std::endl;
std::cout << "Total Space: " << MemoryInfo::formatBytes(totalBytes.QuadPart) << std::endl;
std::cout << "Free Space: " << MemoryInfo::formatBytes(totalFreeBytes.QuadPart) << std::endl;
std::cout << "Available Space: " << MemoryInfo::formatBytes(freeBytesAvailable.QuadPart) << std::endl;
double usedPercent = 100.0 * (1.0 - static_cast<double>(totalFreeBytes.QuadPart) / totalBytes.QuadPart);
std::cout << "Used: " << usedPercent << "%" << std::endl;
}
}
static std::string getDriveType(const std::string& drive) {
UINT type = GetDriveTypeA(drive.c_str());
switch (type) {
case DRIVE_UNKNOWN: return "Unknown";
case DRIVE_NO_ROOT_DIR: return "Invalid Root";
case DRIVE_REMOVABLE: return "Removable";
case DRIVE_FIXED: return "Fixed";
case DRIVE_REMOTE: return "Remote";
case DRIVE_CDROM: return "CD-ROM";
case DRIVE_RAMDISK: return "RAM Disk";
default: return "Unknown";
}
}
};
// 7. Complete Device Profile
class DeviceProfile {
public:
static void generateProfile() {
std::cout << "\n========================================" << std::endl;
std::cout << " DEVICE PROFILE" << std::endl;
std::cout << "========================================" << std::endl;
// System Info
std::cout << "\n--- System ---" << std::endl;
std::cout << "Computer Name: " << SystemInfo::getComputerName() << std::endl;
std::cout << "User Name: " << SystemInfo::getUserName() << std::endl;
std::cout << "OS Version: " << SystemInfo::getWindowsVersion() << std::endl;
std::cout << "System Directory: " << SystemInfo::getSystemDirectory() << std::endl;
// CPU Info
std::cout << "\n";
CPUInfo::displayCPUInfo();
// Memory Info
std::cout << "\n";
MemoryInfo::displayMemoryInfo();
// Battery Info
std::cout << "\n";
BatteryInfo::displayBatteryInfo();
// Display Info
std::cout << "\n";
DisplayInfo::getDisplayInfo();
// Disk Info
std::cout << "\n";
DiskInfo::getDiskInfo("C:\\");
std::cout << "\n========================================" << std::endl;
}
static std::string getJSONProfile() {
// Generate JSON representation of device info
return "{"
"\"computerName\": \"" + SystemInfo::getComputerName() + "","
"\"osVersion\": \"" + SystemInfo::getWindowsVersion() + "","
"\"cpuCores\": " + std::to_string(CPUInfo::getNumberOfCores()) + ","
"\"totalMemory\": \"" + MemoryInfo::formatBytes(MemoryInfo::getMemoryStatus().totalPhysical) + """
"}";
}
};
// Main demonstration
int main() {
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
std::cout << "=== Windows C++ Device Information Examples ===" << std::endl;
// 1. Basic system info
std::cout << "\n--- Basic System Information ---" << std::endl;
std::cout << "Computer: " << SystemInfo::getComputerName() << std::endl;
std::cout << "User: " << SystemInfo::getUserName() << std::endl;
std::cout << "OS: " << SystemInfo::getWindowsVersion() << std::endl;
// 2. CPU information
std::cout << "\n";
CPUInfo::displayCPUInfo();
// 3. Memory information
std::cout << "\n";
MemoryInfo::displayMemoryInfo();
// 4. Battery information
std::cout << "\n";
BatteryInfo::displayBatteryInfo();
// 5. Display information
std::cout << "\n";
DisplayInfo::getDisplayInfo();
// 6. Disk information
std::cout << "\n";
DiskInfo::getDiskInfo("C:\\");
// 7. Complete device profile
std::cout << "\n";
DeviceProfile::generateProfile();
// 8. JSON profile
std::cout << "\n--- JSON Profile ---" << std::endl;
std::cout << DeviceProfile::getJSONProfile() << std::endl;
CoUninitialize();
std::cout << "\n=== All Device Information Examples Completed ===" << std::endl;
return 0;
}Statut du Réseau
Vérifier l'état de la connexion réseau, surveiller les changements réseau et obtenir des informations sur l'adaptateur réseau
Difficulté
7/10
Temps estimé
30 min
Étiquettes
cpp, mobile, network, windows
Prérequis
Intermediate C++, Winsock, Windows Networking API
// Windows C++ Network Status Examples
// Using Windows API for network detection and monitoring
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <winsock2.h>
#include <iphlpapi.h>
#include <ws2tcpip.h>
#include <wininet.h>
#include <wlanapi.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "wininet.lib")
#pragma comment(lib, "wlanapi.lib")
// 1. Basic Network Connectivity Check
class NetworkConnectivity {
public:
enum class ConnectionType {
None,
Ethernet,
WiFi,
Mobile,
VPN,
Unknown
};
static bool isInternetAvailable() {
// Try to connect to a well-known server
DWORD flags;
BOOL result = InternetGetConnectedState(&flags, 0);
if (result) {
std::cout << "Connection flags: 0x" << std::hex << flags << std::dec << std::endl;
if (flags & INTERNET_CONNECTION_MODEM) {
std::cout << "Connection: Modem" << std::endl;
}
if (flags & INTERNET_CONNECTION_LAN) {
std::cout << "Connection: LAN" << std::endl;
}
if (flags & INTERNET_CONNECTION_PROXY) {
std::cout << "Connection: Through Proxy" << std::endl;
}
}
return result != FALSE;
}
static bool pingHost(const std::string& host, int timeoutMs = 5000) {
HANDLE hIcmpFile = IcmpCreateFile();
if (hIcmpFile == INVALID_HANDLE_VALUE) {
return false;
}
// Send ping
char sendData[32] = "Data Buffer";
DWORD replySize = sizeof(ICMP_ECHO_REPLY) + sizeof(sendData);
LPVOID replyBuffer = malloc(replySize);
DWORD dwRetVal = IcmpSendEcho(
hIcmpFile,
inet_addr(host.c_str()),
sendData,
sizeof(sendData),
nullptr,
replyBuffer,
replySize,
timeoutMs
);
bool success = dwRetVal != 0;
if (success) {
PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)replyBuffer;
std::cout << "Ping to " << host << ": " << pEchoReply->RoundTripTime << "ms" << std::endl;
}
free(replyBuffer);
IcmpCloseHandle(hIcmpFile);
return success;
}
static bool isLocalNetworkAvailable() {
// Check if we have a valid IP address
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = nullptr;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
if (pAdapterInfo == nullptr) {
return false;
}
// Make an initial call to get the size
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
if (pAdapterInfo == nullptr) {
return false;
}
}
dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
bool hasAdapter = (dwRetVal == NO_ERROR);
if (hasAdapter) {
pAdapter = pAdapterInfo;
while (pAdapter) {
std::cout << "Adapter: " << pAdapter->Description << std::endl;
std::cout << " IP: " << pAdapter->IpAddressList.IpAddress.String << std::endl;
pAdapter = pAdapter->Next;
}
}
free(pAdapterInfo);
return hasAdapter;
}
};
// 2. Network Adapter Information
class NetworkAdapter {
public:
struct AdapterInfo {
std::string name;
std::string description;
std::string macAddress;
std::string ipAddress;
std::string subnetMask;
std::string gateway;
bool dhcpEnabled;
};
static std::vector<AdapterInfo> getAllAdapters() {
std::vector<AdapterInfo> adapters;
PIP_ADAPTER_INFO pAdapterInfo;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
if (pAdapterInfo == nullptr) {
return adapters;
}
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
}
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
PIP_ADAPTER_INFO pAdapter = pAdapterInfo;
while (pAdapter) {
AdapterInfo info;
info.name = pAdapter->AdapterName;
info.description = pAdapter->Description;
info.macAddress = macToString(pAdapter->Address, pAdapter->AddressLength);
info.ipAddress = pAdapter->IpAddressList.IpAddress.String;
info.subnetMask = pAdapter->IpAddressList.IpMask.String;
info.gateway = pAdapter->GatewayList.IpAddress.String;
info.dhcpEnabled = pAdapter->DhcpEnabled != 0;
adapters.push_back(info);
pAdapter = pAdapter->Next;
}
}
free(pAdapterInfo);
return adapters;
}
static std::string macToString(BYTE* mac, DWORD length) {
char buffer[32];
sprintf_s(buffer, "%02X:%02X:%02X:%02X:%02X:%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return std::string(buffer);
}
static void displayAllAdapters() {
std::vector<AdapterInfo> adapters = getAllAdapters();
std::cout << "=== Network Adapters ===" << std::endl;
std::cout << "Found " << adapters.size() << " adapter(s)" << std::endl;
for (size_t i = 0; i < adapters.size(); i++) {
const AdapterInfo& info = adapters[i];
std::cout << "\nAdapter " << (i + 1) << ":" << std::endl;
std::cout << " Name: " << info.name << std::endl;
std::cout << " Description: " << info.description << std::endl;
std::cout << " MAC: " << info.macAddress << std::endl;
std::cout << " IP: " << info.ipAddress << std::endl;
std::cout << " Subnet: " << info.subnetMask << std::endl;
std::cout << " Gateway: " << info.gateway << std::endl;
std::cout << " DHCP: " << (info.dhcpEnabled ? "Enabled" : "Disabled") << std::endl;
}
}
};
// 3. WiFi Network Information
class WiFiNetwork {
public:
static bool isWiFiAvailable() {
// Check if WiFi adapter exists
PIP_ADAPTER_INFO pAdapterInfo;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen);
}
bool hasWiFi = false;
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
PIP_ADAPTER_INFO pAdapter = pAdapterInfo;
while (pAdapter && !hasWiFi) {
std::string desc = pAdapter->Description;
// Check for WiFi indicators
if (desc.find("Wi-Fi") != std::string::npos ||
desc.find("Wireless") != std::string::npos ||
desc.find("802.11") != std::string::npos) {
hasWiFi = true;
}
pAdapter = pAdapter->Next;
}
}
free(pAdapterInfo);
return hasWiFi;
}
static int getSignalQuality() {
// Signal quality (0-100)
// This would use WLAN API in a full implementation
return -1; // Not available
}
static std::string getSSID() {
// Get current WiFi SSID
// This requires WLAN API calls
return "SSID retrieval requires WLAN API";
}
};
// 4. Network Speed Test
class NetworkSpeed {
public:
static bool testDownloadSpeed(const std::string& url, int timeoutSec = 10) {
// Simple download speed test
HINTERNET hInternet = InternetOpenA("SpeedTest", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hInternet) {
return false;
}
DWORD startTime = GetTickCount();
HINTERNET hUrl = InternetOpenUrlA(hInternet, url.c_str(), NULL, 0,
INTERNET_FLAG_RELOAD, 0);
if (hUrl) {
DWORD bytesRead = 0;
DWORD totalBytes = 0;
char buffer[8192];
DWORD startTime = GetTickCount();
while (InternetReadFile(hUrl, buffer, sizeof(buffer), &bytesRead) && bytesRead > 0) {
totalBytes += bytesRead;
}
DWORD elapsed = GetTickCount() - startTime;
if (elapsed > 0) {
double bytesPerSecond = (totalBytes * 1000.0) / elapsed;
double kbps = bytesPerSecond / 1024.0;
std::cout << "Downloaded: " << totalBytes << " bytes" << std::endl;
std::cout << "Time: " << elapsed << " ms" << std::endl;
std::cout << "Speed: " << kbps << " KB/s" << std::endl;
}
InternetCloseHandle(hUrl);
InternetCloseHandle(hInternet);
return true;
}
InternetCloseHandle(hInternet);
return false;
}
};
// 5. Network Change Monitoring
class NetworkMonitor {
private:
static HWND createMessageWindow() {
// Create a hidden window for receiving messages
WNDCLASSA wc = {};
wc.lpfnWndProc = NetworkMonitor::windowProc;
wc.hInstance = GetModuleHandle(nullptr);
wc.lpszClassName = "NetworkMonitorWindow";
RegisterClassA(&wc);
return CreateWindowExA(
0,
"NetworkMonitorWindow",
"Network Monitor",
0,
0, 0, 0, 0,
HWND_MESSAGE,
nullptr,
GetModuleHandle(nullptr),
nullptr
);
}
static LRESULT CALLBACK windowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
if (uMsg == WM_DEVICECHANGE) {
std::cout << "Network configuration changed" << std::endl;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
public:
static void startMonitoring() {
std::cout << "Starting network monitoring..." << std::endl;
// In a real application, this would register for
// WM_DEVICECHANGE notifications or use NotifyAddrChange
}
};
// 6. DNS Information
class DNSInfo {
public:
static std::string performDNSLookup(const std::string& hostname) {
struct addrinfo hints = {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo* result = nullptr;
int status = getaddrinfo(hostname.c_str(), nullptr, &hints, &result);
std::string ipAddress = "Lookup failed";
if (status == 0 && result) {
char ipBuffer[INET_ADDRSTRLEN];
struct sockaddr_in* addr = (struct sockaddr_in*)result->ai_addr;
if (inet_ntop(AF_INET, &(addr->sin_addr), ipBuffer, sizeof(ipBuffer))) {
ipAddress = ipBuffer;
std::cout << hostname << " -> " << ipAddress << std::endl;
}
freeaddrinfo(result);
}
return ipAddress;
}
static std::string getDNSServers() {
FIXED_INFO* FixedInfo;
ULONG ulOutBufLen = sizeof(FIXED_INFO);
FixedInfo = (FIXED_INFO*)malloc(sizeof(FIXED_INFO));
if (GetNetworkParams(FixedInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) {
free(FixedInfo);
FixedInfo = (FIXED_INFO*)malloc(ulOutBufLen);
}
std::string dnsServers = "";
if (GetNetworkParams(FixedInfo, &ulOutBufLen) == NO_ERROR) {
IP_ADDR_STRING* pIPAddr = &FixedInfo->DnsServerList;
while (pIPAddr) {
dnsServers += pIPAddr->IpAddress.String;
pIPAddr = pIPAddr->Next;
if (pIPAddr) {
dnsServers += ", ";
}
}
}
free(FixedInfo);
return dnsServers;
}
};
// Main demonstration
int main() {
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
std::cout << "=== Windows C++ Network Status Examples ===" << std::endl;
// 1. Check internet connectivity
std::cout << "\n--- Internet Connectivity ---" << std::endl;
bool internet = NetworkConnectivity::isInternetAvailable();
std::cout << "Internet Available: " << (internet ? "Yes" : "No") << std::endl;
// 2. Ping test
std::cout << "\n--- Ping Test ---" << std::endl;
NetworkConnectivity::pingHost("8.8.8.8");
NetworkConnectivity::pingHost("google.com");
// 3. Local network
std::cout << "\n--- Local Network ---" << std::endl;
NetworkConnectivity::isLocalNetworkAvailable();
// 4. Network adapters
std::cout << "\n";
NetworkAdapter::displayAllAdapters();
// 5. WiFi
std::cout << "\n--- WiFi Status ---" << std::endl;
bool wifi = WiFiNetwork::isWiFiAvailable();
std::cout << "WiFi Available: " << (wifi ? "Yes" : "No") << std::endl;
// 6. DNS
std::cout << "\n--- DNS Information ---" << std::endl;
std::string dnsServers = DNSInfo::getDNSServers();
std::cout << "DNS Servers: " << dnsServers << std::endl;
DNSInfo::performDNSLookup("google.com");
DNSInfo::performDNSLookup("localhost");
// 7. Speed test (simulated)
std::cout << "\n--- Speed Test ---" << std::endl;
// NetworkSpeed::testDownloadSpeed("http://example.com");
std::cout << "\n=== All Network Status Examples Completed ===" << std::endl;
WSACleanup();
return 0;
}Vibration et Alertes
Contrôler la vibration de l'appareil et fournir un retour haptique pour les notifications et les alertes
Difficulté
6/10
Temps estimé
25 min
Étiquettes
cpp, mobile, vibration, windows
Prérequis
Intermediate C++, Windows Input API, XInput
// Windows C++ Vibration and Alerts Examples
// For Windows tablets and mobile devices
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
#include <initguid.h>
#include <portabledevicetypes.h>
#include <functiondiscoverykeys_devpkey.h>
// Note: Vibration support on Windows is primarily available on:
// - Windows 10/11 tablets with precision touchpads
// - Windows Mobile devices (legacy)
// - Xbox controllers connected to PC
// 1. Basic Vibration Controller
class VibrationController {
private:
static bool isVibrationSupported() {
// Check if running on a device that supports vibration
// This includes Windows tablets and connected controllers
#ifdef WINAPI_FAMILY_PARTITION
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)
return true; // Windows Phone
#endif
#endif
// Check for tablet/hybrid device
COMPUTER_NAME_FORMAT nameType = ComputerNamePhysicalDnsHostname;
CHAR computerName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = sizeof(computerName);
if (GetComputerNameA(computerName, &size)) {
std::string name(computerName);
// Check for common tablet naming patterns
if (name.find("TABLET") != std::string::npos ||
name.find("Surface") != std::string::npos) {
return true;
}
}
// Check for touchscreen
int value = GetSystemMetrics(SM_MAXIMUMTOUCHES);
return value > 0;
}
public:
static void vibrate(int durationMs = 200) {
if (!isVibrationSupported()) {
std::cout << "Vibration not supported on this device" << std::endl;
return;
}
// On Windows, use InputSimulation or device-specific APIs
std::cout << "Vibrating for " << durationMs << "ms" << std::endl;
// For actual vibration, you would use:
// - Windows.Gaming.Input.Gamepad (UWP)
// - DeviceIoControl with haptic drivers
// - Third-party libraries for specific hardware
// Visual feedback as alternative
FlashWindow(GetForegroundWindow(), TRUE);
}
static void vibratePattern(const std::vector<int>& pattern) {
if (!isVibrationSupported()) {
return;
}
std::cout << "Vibration pattern: [";
for (size_t i = 0; i < pattern.size(); i++) {
std::cout << pattern[i];
if (i < pattern.size() - 1) std::cout << ", ";
}
std::cout << "]" << std::endl;
// Pattern: vibrate, pause, vibrate, pause...
for (int duration : pattern) {
if (duration > 0) {
// Vibrate
std::cout << "Vibrate: " << duration << "ms" << std::endl;
} else {
// Pause
std::cout << "Pause: " << (-duration) << "ms" << std::endl;
}
}
}
static void cancelVibration() {
std::cout << "Vibration cancelled" << std::endl;
}
};
// 2. Xbox Controller Vibration
class ControllerVibration {
public:
struct VibrationIntensity {
double leftMotor; // Low-frequency motor (0.0 - 1.0)
double rightMotor; // High-frequency motor (0.0 - 1.0)
};
static void setControllerVibration(int userIndex, const VibrationIntensity& intensity) {
// For Xbox controllers, use XInput API
std::cout << "Controller " << userIndex << " vibration set:" << std::endl;
std::cout << " Left Motor: " << (intensity.leftMotor * 100) << "%" << std::endl;
std::cout << " Right Motor: " << (intensity.rightMotor * 100) << "%" << std::endl;
// Actual implementation would use XInputSetState:
// XINPUT_VIBRATION vibration;
// vibration.wLeftMotorSpeed = intensity.leftMotor * 65535;
// vibration.wRightMotorSpeed = intensity.rightMotor * 65535;
// XInputSetState(userIndex, &vibration);
}
static void vibrateControllerPulse(int userIndex, double intensity = 0.5) {
VibrationIntensity vib = {intensity, intensity};
setControllerVibration(userIndex, vib);
// Auto-stop after 200ms
// In real implementation, use timer
std::cout << "Pulse for 200ms..." << std::endl;
VibrationIntensity stop = {0.0, 0.0};
// setControllerVibration(userIndex, stop);
}
};
// 3. Notification Patterns
class NotificationVibration {
public:
static void notifyMessage() {
// Short, gentle vibration
VibrationController::vibrate(100);
}
static void notifyEmail() {
// Double vibration
VibrationController::vibrate(150);
Sleep(100);
VibrationController::vibrate(150);
}
static void notifyAlarm() {
// Repeating pattern
std::vector<int> pattern = {500, 200, 500, 200, 500};
VibrationController::vibratePattern(pattern);
}
static void notifyError() {
// Strong, prolonged vibration
VibrationController::vibrate(500);
}
static void notifySuccess() {
// Two short pulses
VibrationController::vibrate(100);
Sleep(50);
VibrationController::vibrate(100);
}
static void notifyIncomingCall() {
// Repeating pulse pattern
std::vector<int> pattern = {300, 300, 300, 300};
VibrationController::vibratePattern(pattern);
}
};
// 4. Haptic Feedback Patterns
class HapticPatterns {
public:
static void lightTap() {
VibrationController::vibrate(50);
}
static void mediumTap() {
VibrationController::vibrate(100);
}
static void heavyTap() {
VibrationController::vibrate(200);
}
static void doubleTap() {
VibrationController::vibrate(75);
Sleep(75);
VibrationController::vibrate(75);
}
static void tripleTap() {
for (int i = 0; i < 3; i++) {
VibrationController::vibrate(75);
Sleep(75);
}
}
static void rampUp() {
// Gradually increasing intensity
for (int i = 1; i <= 5; i++) {
VibrationController::vibrate(50 * i);
Sleep(50);
}
}
static void rampDown() {
// Gradually decreasing intensity
for (int i = 5; i >= 1; i--) {
VibrationController::vibrate(50 * i);
Sleep(50);
}
}
};
// 5. Audio Feedback (Alternative to Vibration)
class AudioFeedback {
public:
static void playNotificationSound() {
MessageBeep(MB_ICONEXCLAMATION);
std::cout << "Playing notification sound" << std::endl;
}
static void playErrorSound() {
MessageBeep(MB_ICONHAND);
std::cout << "Playing error sound" << std::endl;
}
static void playSuccessSound() {
MessageBeep(MB_OK);
std::cout << "Playing success sound" << std::endl;
}
static void playQuestionSound() {
MessageBeep(MB_ICONQUESTION);
std::cout << "Playing question sound" << std::endl;
}
static void beep(int frequency = 750, int durationMs = 300) {
Beep(frequency, durationMs);
std::cout << "Beep: " << frequency << "Hz for " << durationMs << "ms" << std::endl;
}
static void playMorseCode(const std::string& message) {
// Simple Morse code: dot = short, dash = long
std::cout << "Morse code: " << message << std::endl;
for (char c : message) {
switch (toupper(c)) {
case 'S': // ...
beep(750, 100);
Sleep(100);
beep(750, 100);
Sleep(100);
beep(750, 100);
break;
case 'O': // ---
beep(750, 300);
Sleep(100);
beep(750, 300);
Sleep(100);
beep(750, 300);
break;
case ' ':
Sleep(300);
break;
}
Sleep(200);
}
}
};
// 6. Visual Feedback (Screen Flash)
class VisualFeedback {
public:
static void flashScreen(COLORREF color = RGB(255, 255, 255), int durationMs = 100) {
std::cout << "Flash screen: " << durationMs << "ms" << std::endl;
// In a real implementation, create a full-screen window
// with the specified color and hide it after durationMs
}
static void flashTaskbar(HWND hWnd = nullptr) {
if (hWnd == nullptr) {
hWnd = GetForegroundWindow();
}
FLASHWINFO flashInfo = {};
flashInfo.cbSize = sizeof(flashInfo);
flashInfo.hwnd = hWnd;
flashInfo.dwFlags = FLASHW_ALL | FLASHW_TIMERNOFG;
flashInfo.uCount = 3;
flashInfo.dwTimeout = 0;
FlashWindowEx(&flashInfo);
std::cout << "Flashing taskbar" << std::endl;
}
static void startContinuousFlash(HWND hWnd = nullptr) {
if (hWnd == nullptr) {
hWnd = GetForegroundWindow();
}
FLASHWINFO flashInfo = {};
flashInfo.cbSize = sizeof(flashInfo);
flashInfo.hwnd = hWnd;
flashInfo.dwFlags = FLASHW_ALL;
flashInfo.uCount = 10;
flashInfo.dwTimeout = 500;
FlashWindowEx(&flashInfo);
std::cout << "Continuous flashing started" << std::endl;
}
static void stopFlash(HWND hWnd = nullptr) {
if (hWnd == nullptr) {
hWnd = GetForegroundWindow();
}
FLASHWINFO flashInfo = {};
flashInfo.cbSize = sizeof(flashInfo);
flashInfo.hwnd = hWnd;
flashInfo.dwFlags = FLASHW_STOP;
FlashWindowEx(&flashInfo);
std::cout << "Flashing stopped" << std::endl;
}
};
// 7. Combined Feedback System
class FeedbackSystem {
public:
static void alertLow() {
HapticPatterns::lightTap();
AudioFeedback::playNotificationSound();
}
static void alertMedium() {
HapticPatterns::doubleTap();
AudioFeedback::playNotificationSound();
VisualFeedback::flashTaskbar();
}
static void alertHigh() {
HapticPatterns::heavyTap();
AudioFeedback::playErrorSound();
VisualFeedback::startContinuousFlash();
}
static void confirmAction() {
HapticPatterns::mediumTap();
AudioFeedback::playSuccessSound();
}
static void denyAction() {
HapticPatterns::tripleTap();
AudioFeedback::playErrorSound();
}
};
// 8. Accessibility Feedback
class AccessibilityFeedback {
public:
static void notifyScreenReader(const std::string& message) {
// In a real application, use UI Automation
// to announce to screen readers
std::cout << "Screen Reader: " << message << std::endl;
}
static void signalProgressUpdate(int percent) {
// Gentle feedback for progress
if (percent % 25 == 0) {
HapticPatterns::lightTap();
}
}
static void signalCompletion() {
HapticPatterns::doubleTap();
AudioFeedback::playSuccessSound();
}
static void signalBoundary() {
// Alert when reaching limits/edges
HapticPatterns::heavyTap();
AudioFeedback::beep(500, 50);
}
};
// Main demonstration
int main() {
std::cout << "=== Windows C++ Vibration and Alerts Examples ===" << std::endl;
// 1. Basic vibration
std::cout << "\n--- Basic Vibration ---" << std::endl;
VibrationController::vibrate(200);
// 2. Vibration patterns
std::cout << "\n--- Vibration Patterns ---" << std::endl;
std::vector<int> pattern = {100, 50, 200, 50, 100};
VibrationController::vibratePattern(pattern);
// 3. Notification patterns
std::cout << "\n--- Notification Patterns ---" << std::endl;
NotificationVibration::notifyMessage();
NotificationVibration::notifyEmail();
NotificationVibration::notifySuccess();
NotificationVibration::notifyError();
// 4. Haptic patterns
std::cout << "\n--- Haptic Patterns ---" << std::endl;
HapticPatterns::lightTap();
HapticPatterns::doubleTap();
HapticPatterns::rampUp();
// 5. Audio feedback
std::cout << "\n--- Audio Feedback ---" << std::endl;
AudioFeedback::playNotificationSound();
AudioFeedback::playSuccessSound();
AudioFeedback::playErrorSound();
AudioFeedback::beep(1000, 200);
// 6. Visual feedback
std::cout << "\n--- Visual Feedback ---" << std::endl;
VisualFeedback::flashTaskbar();
// 7. Combined feedback
std::cout << "\n--- Combined Feedback ---" << std::endl;
FeedbackSystem::alertLow();
FeedbackSystem::confirmAction();
FeedbackSystem::alertMedium();
// 8. Controller vibration (if Xbox controller connected)
std::cout << "\n--- Controller Vibration ---" << std::endl;
ControllerVibration::VibrationIntensity vib = {0.5, 0.5};
ControllerVibration::setControllerVibration(0, vib);
ControllerVibration::vibrateControllerPulse(0, 0.75);
std::cout << "\n=== All Vibration and Alert Examples Completed ===" << std::endl;
return 0;
}Outils
Outils souvent utilisés avec cet exemple
Associé