Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHESPTRUFRDEEN

Elysia Tools

导航

C++

Windows C++ 移动端功能示例

Windows C++ 移动端专用功能示例,包括获取设备信息、网络状态和振动

案例

这个案例集合中的条目

代码cpp中等

设备信息

获取设备信息,包括型号、系统版本、硬件详细信息和功能

难度

6/10

预计时间

25 min

标签

cpp, mobile, device info, windows

前置条件

Intermediate C++, Windows API, WMI

cpp
// 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;
}
代码cpp中等

网络状态

检查网络连接状态,监控网络变化,并获取网络适配器信息

难度

7/10

预计时间

30 min

标签

cpp, mobile, network, windows

前置条件

Intermediate C++, Winsock, Windows Networking API

cpp
// 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;
}
代码cpp中等

振动和警报

控制设备振动并为通知和警报提供触觉反馈

难度

6/10

预计时间

25 min

标签

cpp, mobile, vibration, windows

前置条件

Intermediate C++, Windows Input API, XInput

cpp
// 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;
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

容器发布前的 Dockerfile 与环境配置审查

检查 Dockerfile 规则、镜像引用格式与环境变量重复键,解释预发布和生产配置差异,形成可核对的容器发布记录。

专题

域名上线前的 DNS、DNSSEC 与 HTTPS 验收

先拟定 DNS 区域记录,再核对在线解析、DNSSEC 委派和实际提供的 HTTPS 证书,为域名上线留下可复核的依据。

专题

重复日历与 ICS 日程安排

跨时区规划并验证重复会议,处理工作日、节假日、冲突和 ICS 导出要求。

专题

API Mock 夹具生成与审阅

生成可重复的 Mock 负载,构造符合格式的边界值,发现易混淆字段名,并在共享临时 Mock 服务前完成复核。

首页
工具3206
案例593
可视化468
文件查看器103
专题236
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融645

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付
小房间家具布局复核与搬入方案交付
FLAC/WAV 无损音源疑点筛查与证据交付
自托管抽奖组件配置复核、嵌入测试与上线交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Development

Windows PE / Linux ELF / Mach-O 二进制头部·节表·导入导出检查器

上传 PE-COFF(.exe/.dll)、ELF 或 Mach-O 二进制,解析 DOS/PE/COFF/可选头、ELF e_ident/程序头/节头、Mach-O 头与加载命令;输出入口点/镜像基址、节表与 RVA↔文件偏移映射、导入/导出表、动态符号与重定位,跨架构注释(x86/x86-64/ARM/AArch64/RISC-V),ASLR/NX/PIE 等安全标志徽章与前 96 字节十六进制预览。

Network

CIDR计算器

从CIDR表示法计算网络信息。支持IPv4和IPv6。

Media

批量图片信息查看器

一次查看多张图片的基本信息 - 尺寸、格式、文件大小和元数据存在情况

Network

IP信息查询

使用地理位置数据库获取IP地址的真实信息,包括位置和ISP详情

Network

IPv4转IPv6

将IPv4地址转换为IPv6地址。支持IPv4映射和IPv4兼容格式。

Validation

MAC地址校验器

验证MAC地址并识别厂商信息

Media

PNG转BMP

将PNG图像转换为BMP格式,具有未压缩质量和广泛兼容性

Data Processing

AI数据规范化器

AI驱动的数据格式规范化工具,使用高级AI分析智能清理和标准化混乱数据

C++

Windows C++ 加密示例

Windows C++ 加密示例,包括哈希计算、AES加密/解密和Base64编码/解码

C++

Windows C++ 数据库示例

使用SQLite的Windows C++数据库操作,包括连接管理、SQL查询和事务处理

C++

Windows C++ 桌面功能示例

Windows C++ 桌面专用功能示例,包括文件对话框、消息框和系统托盘

C++

Windows C++ 错误处理示例

Windows C++ 错误处理示例,包括异常处理、日志记录和参数验证

C++

Windows 文件操作 - C++ 示例

Windows平台C++文件操作示例,包括文本文件读写、文件复制和目录遍历

C++

Windows C++ 图像处理示例

Windows C++ 图像处理示例,包括读取/保存图像、调整大小和使用Windows Imaging Component进行格式转换