Recursos Móveis Windows - Exemplos C#

Exemplos abrangentes de recursos móveis em C# para plataforma Windows incluindo informações do dispositivo, status de rede e integração de hardware

💻 Obtenção de Informações do Dispositivo csharp

🟢 simple ⭐⭐

Obter informações completas do dispositivo incluindo especificações de hardware, detalhes do sistema operacional e capacidades do sistema

⏱️ 20 min 🏷️ csharp, device, hardware, mobile, windows
Prerequisites: WMI basics, Registry access, Win32 API
using System;
using System.Management; // Requires reference to System.Management.dll
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Diagnostics;

class DeviceInformation
{
    // 1. Basic system information
    public static void GetBasicSystemInfo()
    {
        Console.WriteLine("=== Basic System Information ===");

        Console.WriteLine($"Computer Name: {Environment.MachineName}");
        Console.WriteLine($"User Name: {Environment.UserName}");
        Console.WriteLine($"Domain Name: {Environment.UserDomainName}");
        Console.WriteLine($"OS Version: {Environment.OSVersion}");
        Console.WriteLine($".NET Version: {Environment.Version}");
        Console.WriteLine($"Processor Count: {Environment.ProcessorCount}");
        Console.WriteLine($"System Directory: {Environment.SystemDirectory}");
        Console.WriteLine($"Working Directory: {Environment.CurrentDirectory}");
        Console.WriteLine($"Command Line: {Environment.CommandLine}");

        Console.WriteLine($"Is 64-bit OS: {Environment.Is64BitOperatingSystem}");
        Console.WriteLine($"Is 64-bit Process: {Environment.Is64BitProcess}");

        Console.WriteLine($"System Uptime: {GetSystemUptime()}");
        Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}");
    }

    // 2. Hardware information using WMI
    public static void GetHardwareInfo()
    {
        Console.WriteLine("\n=== Hardware Information ===");

        try
        {
            // CPU Information
            using (var searcher = new ManagementObjectSearcher("select * from Win32_Processor"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    Console.WriteLine($"CPU Name: {obj["Name"]}");
                    Console.WriteLine($"CPU Manufacturer: {obj["Manufacturer"]}");
                    Console.WriteLine($"CPU Description: {obj["Description"]}");
                    Console.WriteLine($"CPU Cores: {obj["NumberOfCores"]}");
                    Console.WriteLine($"CPU Logical Processors: {obj["NumberOfLogicalProcessors"]}");
                    Console.WriteLine($"CPU Max Clock Speed: {obj["MaxClockSpeed"]} MHz");
                    break; // Get first CPU
                }
            }

            // Memory Information
            using (var searcher = new ManagementObjectSearcher("select * from Win32_ComputerSystem"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    ulong totalMemory = Convert.ToUInt64(obj["TotalPhysicalMemory"]);
                    Console.WriteLine($"\nTotal RAM: {FormatBytes(totalMemory)}");
                    Console.WriteLine($"System Manufacturer: {obj["Manufacturer"]}");
                    Console.WriteLine($"System Model: {obj["Model"]}");
                    break;
                }
            }

            // BIOS Information
            using (var searcher = new ManagementObjectSearcher("select * from Win32_BIOS"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    Console.WriteLine($"\nBIOS Version: {obj["SMBIOSBIOSVersion"]}");
                    Console.WriteLine($"BIOS Manufacturer: {obj["Manufacturer"]}");
                    Console.WriteLine($"BIOS Release Date: {obj["ReleaseDate"]}");
                    break;
                }
            }

            // Graphics Card Information
            using (var searcher = new ManagementObjectSearcher("select * from Win32_VideoController"))
            {
                Console.WriteLine("\nGraphics Cards:");
                foreach (ManagementObject obj in searcher.Get())
                {
                    Console.WriteLine($"  - {obj["Name"]}");
                    Console.WriteLine($"    Adapter RAM: {obj["AdapterRAM"] != null ? FormatBytes(Convert.ToUInt64(obj["AdapterRAM"])) : "N/A"}");
                    Console.WriteLine($"    Driver Version: {obj["DriverVersion"]}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting hardware info: {ex.Message}");
        }
    }

    // 3. Disk information
    public static void GetDiskInformation()
    {
        Console.WriteLine("\n=== Disk Information ===");

        try
        {
            DriveInfo[] allDrives = DriveInfo.GetDrives();

            foreach (DriveInfo drive in allDrives)
            {
                if (drive.IsReady)
                {
                    Console.WriteLine($"Drive {drive.Name}:");
                    Console.WriteLine($"  Drive type: {drive.DriveType}");
                    Console.WriteLine($"  Volume label: {drive.VolumeLabel}");
                    Console.WriteLine($"  File system: {drive.DriveFormat}");
                    Console.WriteLine($"  Total size: {FormatBytes(drive.TotalSize)}");
                    Console.WriteLine($"  Available space: {FormatBytes(drive.AvailableFreeSpace)}");
                    Console.WriteLine($"  Used space: {FormatBytes(drive.TotalSize - drive.AvailableFreeSpace)}");
                    Console.WriteLine($"  Root directory: {drive.RootDirectory}");
                    Console.WriteLine();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting disk info: {ex.Message}");
        }
    }

    // 4. Network adapters information
    public static void GetNetworkAdapters()
    {
        Console.WriteLine("\n=== Network Adapter Information ===");

        try
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface adapter in adapters)
            {
                if (adapter.OperationalStatus == OperationalStatus.Up)
                {
                    Console.WriteLine($"Adapter: {adapter.Name}");
                    Console.WriteLine($"  Type: {adapter.NetworkInterfaceType}");
                    Console.WriteLine($"  Status: {adapter.OperationalStatus}");
                    Console.WriteLine($"  Speed: {adapter.Speed:N0} bps");
                    Console.WriteLine($"  Description: {adapter.Description}");

                    IPInterfaceProperties properties = adapter.GetIPProperties();
                    foreach (UnicastIPAddressInformation ip in properties.UnicastAddresses)
                    {
                        if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            Console.WriteLine($"  IPv4 Address: {ip.Address}");
                        }
                        else if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                        {
                            Console.WriteLine($"  IPv6 Address: {ip.Address}");
                        }
                    }

                    if (adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                    {
                        Console.WriteLine("  Connection Type: Wireless");
                    }
                    else if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                    {
                        Console.WriteLine("  Connection Type: Ethernet");
                    }

                    Console.WriteLine();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting network adapter info: {ex.Message}");
        }
    }

    // 5. Display information
    public static void GetDisplayInformation()
    {
        Console.WriteLine("\n=== Display Information ===");

        try
        {
            // Screen dimensions
            Rectangle primaryScreen = Screen.PrimaryScreen.Bounds;
            Console.WriteLine($"Primary Screen:");
            Console.WriteLine($"  Resolution: {primaryScreen.Width} x {primaryScreen.Height}");
            Console.WriteLine($"  Working Area: {Screen.PrimaryScreen.WorkingArea.Width} x {Screen.PrimaryScreen.WorkingArea.Height}");

            // Multiple screens
            Screen[] allScreens = Screen.AllScreens;
            Console.WriteLine($"\nTotal number of screens: {allScreens.Length}");

            for (int i = 0; i < allScreens.Length; i++)
            {
                Console.WriteLine($"Screen {i + 1}: {allScreens[i].Bounds.Width} x {allScreens[i].Bounds.Height}");
                Console.WriteLine($"  Primary: {allScreens[i].Primary}");
                Console.WriteLine($"  BitsPerPixel: {allScreens[i].BitsPerPixel}");
            }

            // DPI information (Windows 10+)
            using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
            {
                float dpiX = graphics.DpiX;
                float dpiY = graphics.DpiY;
                Console.WriteLine($"\nDPI: {dpiX} x {dpiY}");
                Console.WriteLine($"Scaling: {(dpiX / 96.0f) * 100:F0}%");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting display info: {ex.Message}");
        }
    }

    // 6. Battery information (for laptops/mobile devices)
    public static void GetBatteryInformation()
    {
        Console.WriteLine("\n=== Battery Information ===");

        try
        {
            PowerStatus powerStatus = System.Windows.Forms.SystemInformation.PowerStatus;

            Console.WriteLine($"Power Source: {powerStatus.PowerLineStatus}");
            Console.WriteLine($"Battery Charge Status: {powerStatus.BatteryChargeStatus}");
            Console.WriteLine($"Battery Life Percent: {powerStatus.BatteryLifePercent * 100:F1}%");

            if (powerStatus.BatteryLifeRemaining > 0)
            {
                TimeSpan remainingTime = TimeSpan.FromSeconds(powerStatus.BatteryLifeRemaining);
                Console.WriteLine($"Battery Life Remaining: {remainingTime.Hours:D2}:{remainingTime.Minutes:D2}");
            }

            // Get detailed battery information using WMI
            try
            {
                using (var searcher = new ManagementObjectSearcher("select * from Win32_Battery"))
                {
                    foreach (ManagementObject battery in searcher.Get())
                    {
                        Console.WriteLine($"\nBattery Details:");
                        Console.WriteLine($"  Device ID: {battery["DeviceID"]}");
                        Console.WriteLine($"  Name: {battery["Name"]}");
                        Console.WriteLine($"  Status: {battery["Status"]}");
                        Console.WriteLine($"  Chemistry: {battery["Chemistry"]}");
                        Console.WriteLine($"  Design Capacity: {battery["DesignCapacity"]} mWh");
                        Console.WriteLine($"  Full Charged Capacity: {battery["FullChargedCapacity"]} mWh");

                        if (battery["EstimatedChargeRemaining"] != null)
                        {
                            Console.WriteLine($"  Estimated Charge: {battery["EstimatedChargeRemaining"]}%");
                        }

                        if (battery["EstimatedRunTime"] != null)
                        {
                            TimeSpan runTime = TimeSpan.FromSeconds(Convert.ToInt32(battery["EstimatedRunTime"]) * 60);
                            Console.WriteLine($"  Estimated Run Time: {runTime.Hours:D2}:{runTime.Minutes:D2}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Battery details not available: {ex.Message}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting battery info: {ex.Message}");
        }
    }

    // 7. Software information
    public static void GetSoftwareInformation()
    {
        Console.WriteLine("\n=== Software Information ===");

        try
        {
            // Get installed programs from registry
            Console.WriteLine("Installed Software (first 10):");

            const string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey))
            {
                if (key != null)
                {
                    string[] subKeyNames = key.GetSubKeyNames();
                    int count = 0;

                    foreach (string subKeyName in subKeyNames.Take(10))
                    {
                        using (RegistryKey subKey = key.OpenSubKey(subKeyName))
                        {
                            if (subKey != null)
                            {
                                string displayName = subKey.GetValue("DisplayName")?.ToString();
                                string version = subKey.GetValue("DisplayVersion")?.ToString();
                                string publisher = subKey.GetValue("Publisher")?.ToString();

                                if (!string.IsNullOrEmpty(displayName))
                                {
                                    Console.WriteLine($"  - {displayName}");
                                    if (!string.IsNullOrEmpty(version))
                                        Console.WriteLine($"    Version: {version}");
                                    if (!string.IsNullOrEmpty(publisher))
                                        Console.WriteLine($"    Publisher: {publisher}");
                                    count++;
                                }
                            }
                        }
                    }

                    if (count == 0)
                    {
                        Console.WriteLine("  No software information available");
                    }
                }
            }

            // Get running processes
            Console.WriteLine("\nRunning Processes (first 10):");
            Process[] processes = Process.GetProcesses();

            foreach (Process process in processes.Take(10))
            {
                try
                {
                    string processName = process.ProcessName;
                    string fileName = process.MainModule?.FileName ?? "N/A";
                    long memoryUsage = process.WorkingSet64;

                    Console.WriteLine($"  - {processName}");
                    Console.WriteLine($"    Path: {fileName}");
                    Console.WriteLine($"    Memory: {FormatBytes(memoryUsage)}");
                    Console.WriteLine($"    PID: {process.Id}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"  - {process.ProcessName}: {ex.Message}");
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error getting software info: {ex.Message}");
        }
    }

    // 8. Device capabilities
    public static void GetDeviceCapabilities()
    {
        Console.WriteLine("\n=== Device Capabilities ===");

        try
        {
            // Check for touch capabilities (Windows 8+)
            try
            {
                int touchCapabilities = GetSystemMetrics(95); // SM_MAXIMUMTOUCHES
                Console.WriteLine($"Touch Support: {(touchCapabilities > 0 ? $"Yes - {touchCapabilities} points" : "No")}");
            }
            catch
            {
                Console.WriteLine("Touch Support: Unable to determine");
            }

            // Check for tablet mode
            try
            {
                bool tabletMode = IsTabletMode();
                Console.WriteLine($"Tablet Mode: {tabletMode}");
            }
            catch
            {
                Console.WriteLine("Tablet Mode: Unable to determine");
            }

            // Check for network availability
            bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
            Console.WriteLine($"Network Available: {isNetworkAvailable}");

            // Check for internet connectivity
            try
            {
                bool hasInternet = CheckInternetConnectivity();
                Console.WriteLine($"Internet Connected: {hasInternet}");
            }
            catch
            {
                Console.WriteLine("Internet Connected: Unable to determine");
            }

            // Check for sleep/hibernate support
            PowerCapabilities powerCaps = GetPowerCapabilities();
            Console.WriteLine($"Sleep Supported: {powerCaps.SleepSupported}");
            Console.WriteLine($"Hibernate Supported: {powerCaps.HibernateSupported}");

            // Check for secure boot
            try
            {
                bool secureBoot = IsSecureBootEnabled();
                Console.WriteLine($"Secure Boot: {secureBoot}");
            }
            catch
            {
                Console.WriteLine("Secure Boot: Unable to determine");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error checking device capabilities: {ex.Message}");
        }
    }

    // Helper methods
    private static TimeSpan GetSystemUptime()
    {
        using (var uptime = new PerformanceCounter("System", "System Up Time"))
        {
            uptime.NextValue(); // Call this once to get the correct value
            return TimeSpan.FromSeconds(uptime.NextValue());
        }
    }

    private static string FormatBytes(long bytes)
    {
        string[] sizes = { "B", "KB", "MB", "GB", "TB" };
        int order = 0;
        double size = bytes;

        while (size >= 1024 && order < sizes.Length - 1)
        {
            order++;
            size /= 1024;
        }

        return $"{size:F2} {sizes[order]}";
    }

    // Win32 API declarations
    [DllImport("user32.dll")]
    private static extern int GetSystemMetrics(int nIndex);

    [DllImport("powrprof.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern bool GetPwrDiskSpindown(ref int policy);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SystemParametersInfo(int uiAction, int uiParam, IntPtr pvParam, int fWinIni);

    private static bool IsTabletMode()
    {
        // Simplified check - in a real app, you'd use more sophisticated detection
        try
        {
            var query = new SelectQuery("Win32_SystemEnclosure");
            using (var searcher = new ManagementObjectSearcher(query))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    ushort[] chassisTypes = (ushort[])obj["ChassisTypes"];
                    if (chassisTypes.Length > 0)
                    {
                        // 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 are portable types
                        ushort chassisType = chassisTypes[0];
                        return new[] { 8, 9, 10, 11, 12, 14, 18, 21, 31, 32 }.Contains(chassisType);
                    }
                }
            }
        }
        catch
        {
            // Ignore errors
        }
        return false;
    }

    private static bool CheckInternetConnectivity()
    {
        try
        {
            using (var ping = new System.Net.NetworkInformation.Ping())
            {
                var reply = ping.Send("8.8.8.8", 3000); // Google DNS
                return reply.Status == System.Net.NetworkInformation.IPStatus.Success;
            }
        }
        catch
        {
            return false;
        }
    }

    private struct PowerCapabilities
    {
        public bool SleepSupported;
        public bool HibernateSupported;
    }

    private static PowerCapabilities GetPowerCapabilities()
    {
        PowerCapabilities caps = new PowerCapabilities();
        caps.SleepSupported = true; // Simplified
        caps.HibernateSupported = true; // Simplified
        return caps;
    }

    private static bool IsSecureBootEnabled()
    {
        try
        {
            using (var searcher = new ManagementObjectSearcher("root\SecurityCenter2", "SELECT * FROM AntivirusProduct"))
            {
                // This is a placeholder - real secure boot detection is more complex
                return false;
            }
        }
        catch
        {
            return false;
        }
    }

    // Main method for demonstration
    static void Main(string[] args)
    {
        Console.WriteLine("=== C# Device Information Examples ===\n");

        try
        {
            GetBasicSystemInfo();
            GetHardwareInfo();
            GetDiskInformation();
            GetNetworkAdapters();
            GetDisplayInformation();
            GetBatteryInformation();
            GetSoftwareInformation();
            GetDeviceCapabilities();

            Console.WriteLine("\nDevice information collection completed!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error collecting device information: {ex.Message}");
        }
    }
}

💻 Vibração e Feedback Háptico csharp

undefined advanced ⭐⭐⭐

Implementar padrões de vibração do dispositivo e feedback háptico para notificações móveis

⏱️ 25 min 🏷️ csharp, vibration, haptic, mobile, windows
Prerequisites: Async/await programming, Native API interop, Mobile development
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Diagnostics;

// Note: Vibration functionality depends on the device capabilities
// This example demonstrates the API structure, but actual vibration
// support varies by device and platform (Windows Phone, UWP, etc.)

class VibrationController
{
    // Import Windows Phone 8+ vibration API
    [DllImport("vibrate.dll", EntryPoint = "Vibrate")]
    private static extern void Vibrate(int durationMs);

    [DllImport("vibrate.dll", EntryPoint = "StopVibration")]
    private static extern void StopVibration();

    // For UWP/Windows 10+ devices, you'd use:
    // Windows.Phone.Devices.Notification.VibrationDevice

    private VibrationDevice _vibrationDevice;
    private bool _isVibrationSupported;
    private CancellationTokenSource _vibrationCancellation;

    public VibrationController()
    {
        InitializeVibration();
    }

    // 1. Initialize vibration controller
    private void InitializeVibration()
    {
        try
        {
            // Check if vibration is supported
            _isVibrationSupported = CheckVibrationSupport();

            if (_isVibrationSupported)
            {
                Console.WriteLine("Vibration is supported on this device");
                // Initialize the vibration device
                _vibrationDevice = new VibrationDevice();
            }
            else
            {
                Console.WriteLine("Vibration is not supported on this device");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error initializing vibration: {ex.Message}");
            _isVibrationSupported = false;
        }
    }

    // 2. Check vibration support
    private bool CheckVibrationSupport()
    {
        try
        {
            // Try to detect if this is a mobile device
            bool isMobile = IsMobileDevice();
            bool hasVibrationHardware = HasVibrationHardware();

            return isMobile && hasVibrationHardware;
        }
        catch
        {
            return false;
        }
    }

    private bool IsMobileDevice()
    {
        // Check device characteristics
        bool isTablet = SystemInformation.TabletMode;
        bool hasTouchScreen = SystemInformation.TouchEnabled;
        bool hasAccelerometer = CheckAccelerometerSupport();

        return isTablet || hasTouchScreen || hasAccelerometer;
    }

    private bool HasVibrationHardware()
    {
        // Check WMI for vibration/haptic feedback devices
        try
        {
            var searcher = new ManagementObjectSearcher(
                "SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%Haptic%' OR Name LIKE '%Vibration%' OR Name LIKE '%Force%'");

            foreach (ManagementObject device in searcher.Get())
            {
                string deviceName = device["Name"].ToString().ToLower();
                if (deviceName.Contains("haptic") || deviceName.Contains("vibration") || deviceName.Contains("force feedback"))
                {
                    return true;
                }
            }
        }
        catch
        {
            // WMI not available or no access
        }

        return false;
    }

    private bool CheckAccelerometerSupport()
    {
        try
        {
            // Check for accelerometer sensors
            var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Name LIKE '%Accelerometer%'");
            return searcher.Get().Count > 0;
        }
        catch
        {
            return false;
        }
    }

    // 3. Simple vibration
    public void Vibrate(int durationMs)
    {
        if (!_isVibrationSupported)
        {
            Console.WriteLine($"Vibration not supported. Simulating {durationMs}ms vibration...");
            SimulateVibration(durationMs);
            return;
        }

        try
        {
            Console.WriteLine($"Vibrating for {durationMs}ms...");

            // Use platform-specific API
            if (_vibrationDevice != null)
            {
                _vibrationDevice.Vibrate(TimeSpan.FromMilliseconds(durationMs));
            }
            else
            {
                // Fallback to native API
                Vibrate(durationMs);
            }

            // Simulate the duration since we can't actually wait
            Thread.Sleep(durationMs);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error during vibration: {ex.Message}");
        }
    }

    // 4. Vibration pattern
    public void VibratePattern(VibrationPattern pattern)
    {
        if (!_isVibrationSupported)
        {
            Console.WriteLine($"Vibration not supported. Simulating pattern: {pattern.Name}");
            SimulateVibrationPattern(pattern);
            return;
        }

        Console.WriteLine($"Playing vibration pattern: {pattern.Name}");

        try
        {
            foreach (var segment in pattern.Segments)
            {
                if (segment.Duration > 0)
                {
                    Vibrate(segment.Duration);
                }

                if (segment.Pause > 0)
                {
                    StopVibration();
                    Thread.Sleep(segment.Pause);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error playing vibration pattern: {ex.Message}");
        }
    }

    // 5. Async vibration with cancellation
    public async Task VibrateAsync(int durationMs, CancellationToken cancellationToken = default)
    {
        if (!_isVibrationSupported)
        {
            Console.WriteLine($"Vibration not supported. Simulating async {durationMs}ms vibration...");
            await SimulateVibrationAsync(durationMs, cancellationToken);
            return;
        }

        try
        {
            Console.WriteLine($"Starting async vibration for {durationMs}ms...");

            _vibrationCancellation = new CancellationTokenSource();
            var combinedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _vibrationCancellation.Token).Token;

            if (_vibrationDevice != null)
            {
                _vibrationDevice.Vibrate(TimeSpan.FromMilliseconds(durationMs));
            }
            else
            {
                Vibrate(durationMs);
            }

            // Wait for vibration to complete or cancellation
            await Task.Delay(durationMs, combinedToken);

            Console.WriteLine("Async vibration completed");
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Vibration cancelled");
            StopVibration();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error during async vibration: {ex.Message}");
        }
    }

    // 6. Stop vibration
    public void StopVibration()
    {
        try
        {
            if (_vibrationDevice != null)
            {
                _vibrationDevice.Stop();
            }
            else
            {
                // Fallback to native API
                StopVibration();
            }

            _vibrationCancellation?.Cancel();
            Console.WriteLine("Vibration stopped");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error stopping vibration: {ex.Message}");
        }
    }

    // 7. Continuous vibration monitoring
    public async Task StartContinuousVibration(int onDurationMs, int offDurationMs, CancellationToken cancellationToken = default)
    {
        if (!_isVibrationSupported)
        {
            Console.WriteLine($"Vibration not supported. Simulating continuous vibration...");
            await SimulateContinuousVibration(onDurationMs, offDurationMs, cancellationToken);
            return;
        }

        Console.WriteLine($"Starting continuous vibration: {onDurationMs}ms ON, {offDurationMs}ms OFF");

        try
        {
            while (!cancellationToken.IsCancellationRequested)
            {
                // Vibrate
                await VibrateAsync(onDurationMs, cancellationToken);

                if (cancellationToken.IsCancellationRequested) break;

                // Pause
                Console.WriteLine($"Pausing for {offDurationMs}ms...");
                await Task.Delay(offDurationMs, cancellationToken);
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Continuous vibration cancelled");
        }
        finally
        {
            StopVibration();
        }
    }

    // 8. Notification vibration patterns
    public void PlayNotificationVibration(NotificationType type)
    {
        VibrationPattern pattern = GetNotificationPattern(type);
        VibratePattern(pattern);
    }

    private VibrationPattern GetNotificationPattern(NotificationType type)
    {
        switch (type)
        {
            case NotificationType.NewMessage:
                return new VibrationPattern("New Message", new[]
                {
                    new VibrationSegment(100, 50),
                    new VibrationSegment(100, 50),
                    new VibrationSegment(100, 0)
                });

            case NotificationType.Email:
                return new VibrationPattern("Email", new[]
                {
                    new VibrationSegment(200, 100),
                    new VibrationSegment(200, 100),
                    new VibrationSegment(200, 0)
                });

            case NotificationType.Alert:
                return new VibrationPattern("Alert", new[]
                {
                    new VibrationSegment(500, 200),
                    new VibrationSegment(500, 200),
                    new VibrationSegment(500, 0)
                });

            case NotificationType.Success:
                return new VibrationPattern("Success", new[]
                {
                    new VibrationSegment(150, 50),
                    new VibrationSegment(50, 50),
                    new VibrationSegment(150, 0)
                });

            case NotificationType.Error:
                return new VibrationPattern("Error", new[]
                {
                    new VibrationSegment(300, 100),
                    new VibrationSegment(100, 100),
                    new VibrationSegment(300, 100),
                    new VibrationSegment(100, 100),
                    new VibrationSegment(300, 0)
                });

            default:
                return new VibrationPattern("Default", new[]
                {
                    new VibrationSegment(200, 0)
                });
        }
    }

    // Simulation methods for devices without vibration support
    private void SimulateVibration(int durationMs)
    {
        Console.WriteLine($"[SIMULATION] Vibrating for {durationMs}ms...");
        Thread.Sleep(durationMs);
        Console.WriteLine("[SIMULATION] Vibration completed");
    }

    private void SimulateVibrationPattern(VibrationPattern pattern)
    {
        Console.WriteLine($"[SIMULATION] Playing pattern: {pattern.Name}");

        foreach (var segment in pattern.Segments)
        {
            if (segment.Duration > 0)
            {
                Console.WriteLine($"[SIMULATION] VIBRATE {segment.Duration}ms");
                Thread.Sleep(segment.Duration);
            }

            if (segment.Pause > 0)
            {
                Console.WriteLine($"[SIMULATION] PAUSE {segment.Pause}ms");
                Thread.Sleep(segment.Pause);
            }
        }
    }

    private async Task SimulateVibrationAsync(int durationMs, CancellationToken cancellationToken)
    {
        Console.WriteLine($"[SIMULATION] Async vibrating for {durationMs}ms...");
        await Task.Delay(durationMs, cancellationToken);
        Console.WriteLine("[SIMULATION] Async vibration completed");
    }

    private async Task SimulateContinuousVibration(int onDurationMs, int offDurationMs, CancellationToken cancellationToken)
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            Console.WriteLine($"[SIMULATION] VIBRATE {onDurationMs}ms");
            await Task.Delay(onDurationMs, cancellationToken);

            if (cancellationToken.IsCancellationRequested) break;

            Console.WriteLine($"[SIMULATION] PAUSE {offDurationMs}ms");
            await Task.Delay(offDurationMs, cancellationToken);
        }
    }

    public void Dispose()
    {
        StopVibration();
        _vibrationDevice?.Dispose();
        _vibrationCancellation?.Dispose();
    }
}

// Helper classes
public class VibrationDevice
{
    public void Vibrate(TimeSpan duration)
    {
        Console.WriteLine($"VibrationDevice: Vibrate for {duration.TotalMilliseconds}ms");
        // Implementation would use platform-specific APIs
    }

    public void Stop()
    {
        Console.WriteLine("VibrationDevice: Stop vibration");
        // Implementation would use platform-specific APIs
    }

    public void Dispose()
    {
        Stop();
    }
}

public class VibrationPattern
{
    public string Name { get; set; }
    public List<VibrationSegment> Segments { get; set; }

    public VibrationPattern(string name, List<VibrationSegment> segments)
    {
        Name = name;
        Segments = segments;
    }
}

public class VibrationSegment
{
    public int Duration { get; set; }  // Vibration duration in ms
    public int Pause { get; set; }     // Pause duration in ms

    public VibrationSegment(int duration, int pause)
    {
        Duration = duration;
        Pause = pause;
    }
}

public enum NotificationType
{
    NewMessage,
    Email,
    Alert,
    Success,
    Error,
    Reminder
}

// Demonstration class
class VibrationExamples
{
    public static async Task RunAllExamples()
    {
        Console.WriteLine("=== C# Vibration and Haptic Feedback Examples ===\n");

        using (var vibrationController = new VibrationController())
        {
            // 1. Basic vibration
            Console.WriteLine("1. Basic Vibration Test:");
            vibrationController.Vibrate(500);
            Console.WriteLine();

            // 2. Notification vibrations
            Console.WriteLine("2. Notification Vibration Patterns:");
            var notificationTypes = Enum.GetValues(typeof(NotificationType));
            foreach (NotificationType type in notificationTypes)
            {
                Console.WriteLine($"\nPlaying {type} notification vibration:");
                vibrationController.PlayNotificationVibration(type);
                Thread.Sleep(1000);
            }

            // 3. Custom vibration pattern
            Console.WriteLine("\n3. Custom Vibration Pattern:");
            var customPattern = new VibrationPattern("Custom", new List<VibrationSegment>
            {
                new VibrationSegment(100, 50),
                new VibrationSegment(100, 50),
                new VibrationSegment(200, 100),
                new VibrationSegment(50, 50),
                new VibrationSegment(50, 50),
                new VibrationSegment(100, 0)
            });
            vibrationController.VibratePattern(customPattern);

            // 4. Async vibration
            Console.WriteLine("\n4. Async Vibration:");
            await vibrationController.VibrateAsync(1000);

            // 5. Continuous vibration (for demonstration, just run for 5 seconds)
            Console.WriteLine("\n5. Continuous Vibration (5 seconds):");
            var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            await vibrationController.StartContinuousVibration(200, 300, cts.Token);

            Console.WriteLine("\nVibration examples completed!");
        }
    }

    // Main method
    static void Main(string[] args)
    {
        Console.WriteLine("Starting vibration examples...");
        Console.WriteLine("Note: Vibration support depends on device hardware.\n");

        try
        {
            RunAllExamples().GetAwaiter().GetResult();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error running vibration examples: {ex.Message}");
        }

        Console.WriteLine("\nPress Enter to exit...");
        Console.ReadLine();
    }
}

💻 Monitoramento de Status de Rede csharp

🟡 intermediate ⭐⭐⭐

Monitorar conectividade de rede, largura de banda e tipos de conexão com atualizações em tempo real

⏱️ 30 min 🏷️ csharp, network, monitoring, mobile, windows
Prerequisites: Network programming, Asynchronous programming, System.Net
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;

class NetworkStatusMonitor
{
    private static Timer _networkTimer;
    private static bool _isMonitoring = false;
    private static List<NetworkEvent> _networkEvents = new List<NetworkEvent>();

    // 1. Check network availability
    public static void CheckNetworkAvailability()
    {
        Console.WriteLine("=== Network Availability Check ===");

        bool isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
        Console.WriteLine($"Network Available: {isNetworkAvailable}");

        // Get all network interfaces
        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
        Console.WriteLine($"Total Network Interfaces: {interfaces.Length}");

        foreach (NetworkInterface adapter in interfaces)
        {
            Console.WriteLine($"\nAdapter: {adapter.Name}");
            Console.WriteLine($"  Type: {adapter.NetworkInterfaceType}");
            Console.WriteLine($"  Status: {adapter.OperationalStatus}");
            Console.WriteLine($"  Speed: {adapter.Speed:N0} bps");
            Console.WriteLine($"  Supports Multicast: {adapter.SupportsMulticast}");

            if (adapter.OperationalStatus == OperationalStatus.Up)
            {
                IPInterfaceProperties properties = adapter.GetIPProperties();
                Console.WriteLine($"  DNS Enabled: {properties.IsDnsEnabled}");
                Console.WriteLine($"  DNS Suffix: {properties.DnsSuffix}");
            }
        }
    }

    // 2. Test internet connectivity
    public static async Task TestInternetConnectivity()
    {
        Console.WriteLine("\n=== Internet Connectivity Test ===");

        string[] testHosts = {
            "8.8.8.8",          // Google DNS
            "1.1.1.1",          // Cloudflare DNS
            "www.google.com",    // Google
            "www.microsoft.com", // Microsoft
            "www.github.com"     // GitHub
        };

        foreach (string host in testHosts)
        {
            Console.Write($"Testing {host}... ");

            try
            {
                Stopwatch stopwatch = Stopwatch.StartNew();

                using (var ping = new Ping())
                {
                    PingReply reply = await ping.SendPingAsync(host, 3000);
                    stopwatch.Stop();

                    if (reply.Status == IPStatus.Success)
                    {
                        Console.WriteLine($"✓ Success ({stopwatch.ElapsedMilliseconds}ms, TTL: {reply.Options.Ttl})");
                        Console.WriteLine($"  Address: {reply.Address}");
                        Console.WriteLine($"  Buffer size: {reply.Buffer.Length} bytes");
                    }
                    else
                    {
                        Console.WriteLine($"✗ Failed: {reply.Status}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error: {ex.Message}");
            }
        }
    }

    // 3. Monitor network bandwidth
    public static void MonitorNetworkBandwidth()
    {
        Console.WriteLine("\n=== Network Bandwidth Monitor ===");

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces()
            .Where(i => i.OperationalStatus == OperationalStatus.Up &&
                        i.NetworkInterfaceType != NetworkInterfaceType.Loopback)
            .ToArray();

        if (interfaces.Length == 0)
        {
            Console.WriteLine("No active network interfaces found");
            return;
        }

        Dictionary<string, long> previousBytes = new Dictionary<string, long>();

        // Initialize previous values
        foreach (NetworkInterface adapter in interfaces)
        {
            IPv4InterfaceStatistics stats = adapter.GetIPv4Statistics();
            previousBytes[adapter.Name] = stats.BytesReceived + stats.BytesSent;
        }

        Console.WriteLine("Monitoring network bandwidth for 10 seconds...");
        Console.WriteLine("(Press Ctrl+C to stop)\n");

        DateTime startTime = DateTime.Now;
        int iteration = 0;

        while (DateTime.Now - startTime < TimeSpan.FromSeconds(10))
        {
            iteration++;
            Console.WriteLine($"=== Iteration {iteration} - {DateTime.Now:HH:mm:ss} ===");

            foreach (NetworkInterface adapter in interfaces)
            {
                IPv4InterfaceStatistics stats = adapter.GetIPv4Statistics();
                long totalBytes = stats.BytesReceived + stats.BytesSent;

                if (previousBytes.ContainsKey(adapter.Name))
                {
                    long previousTotal = previousBytes[adapter.Name];
                    long bytesInSecond = totalBytes - previousTotal;

                    double downloadSpeed = (stats.BytesReceived - previousTotal) / 1024.0; // KB/s
                    double uploadSpeed = bytesInSecond / 1024.0 - downloadSpeed; // Approximate

                    Console.WriteLine($"{adapter.Name}:");
                    Console.WriteLine($"  Download: {downloadSpeed:F2} KB/s");
                    Console.WriteLine($"  Upload: {uploadSpeed:F2} KB/s");
                    Console.WriteLine($"  Total: {bytesInSecond / 1024.0:F2} KB/s");
                }

                previousBytes[adapter.Name] = totalBytes;
            }

            Thread.Sleep(1000);
            Console.WriteLine();
        }
    }

    // 4. Network event logging
    public static void StartNetworkEventMonitoring()
    {
        Console.WriteLine("=== Network Event Monitoring ===");

        _networkEvents.Clear();
        _isMonitoring = true;

        // Start monitoring timer
        _networkTimer = new Timer(MonitorNetworkChanges, null, 0, 2000);

        Console.WriteLine("Network monitoring started. Press Enter to stop...");
        Console.ReadLine();

        StopNetworkEventMonitoring();
    }

    private static void MonitorNetworkChanges(object state)
    {
        if (!_isMonitoring) return;

        try
        {
            bool currentNetworkStatus = NetworkInterface.GetIsNetworkAvailable();
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            // Check for network availability changes
            if (_networkEvents.Count == 0 || _networkEvents.Last().NetworkAvailable != currentNetworkStatus)
            {
                NetworkEvent newEvent = new NetworkEvent
                {
                    Timestamp = timestamp,
                    EventType = "Network Status Change",
                    NetworkAvailable = currentNetworkStatus,
                    Message = currentNetworkStatus ? "Network became available" : "Network became unavailable"
                };

                _networkEvents.Add(newEvent);
                Console.WriteLine($"[{timestamp}] {newEvent.Message}");
            }

            // Check for interface changes
            NetworkInterface[] currentInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            // In a real implementation, you'd compare with previous state
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error monitoring network: {ex.Message}");
        }
    }

    private static void StopNetworkEventMonitoring()
    {
        _isMonitoring = false;
        _networkTimer?.Dispose();
        Console.WriteLine("\nNetwork monitoring stopped");

        Console.WriteLine("\n=== Network Events Log ===");
        foreach (NetworkEvent evt in _networkEvents)
        {
            Console.WriteLine($"[{evt.Timestamp}] {evt.EventType}: {evt.Message}");
        }
    }

    // 5. Connection type detection
    public static void DetectConnectionTypes()
    {
        Console.WriteLine("\n=== Connection Type Detection ===");

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces()
            .Where(i => i.OperationalStatus == OperationalStatus.Up)
            .ToArray();

        foreach (NetworkInterface adapter in interfaces)
        {
            Console.WriteLine($\nAdapter: {adapter.Name});
            Console.WriteLine($"  Type: {GetConnectionTypeDescription(adapter.NetworkInterfaceType)}");

            if (adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
            {
                Console.WriteLine("  This is a wireless (Wi-Fi) connection");
                DetectWiFiDetails(adapter);
            }
            else if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
            {
                Console.WriteLine("  This is a wired (Ethernet) connection");
            }
            else if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ppp)
            {
                Console.WriteLine("  This is a dial-up/VPN connection");
            }

            // Check for mobile broadband
            if (adapter.Description.ToLower().Contains("mobile") ||
                adapter.Description.ToLower().Contains("cellular") ||
                adapter.Description.ToLower().Contains("lte"))
            {
                Console.WriteLine("  This appears to be a mobile broadband connection");
            }
        }
    }

    private static void DetectWiFiDetails(NetworkInterface adapter)
    {
        // Note: WiFi details typically require specialized libraries
        // This is a simplified implementation

        Console.WriteLine($"  Description: {adapter.Description}");

        // Check if it's likely 5GHz based on speed
        if (adapter.Speed > 400000000) // > 400 Mbps suggests 5GHz
        {
            Console.WriteLine("  Likely frequency band: 5 GHz");
        }
        else
        {
            Console.WriteLine("  Likely frequency band: 2.4 GHz");
        }

        // Get signal strength (simplified - would need native API for real signal strength)
        Console.WriteLine("  Signal quality: Unable to determine without native APIs");
    }

    private static string GetConnectionTypeDescription(NetworkInterfaceType type)
    {
        switch (type)
        {
            case NetworkInterfaceType.Ethernet:
                return "Ethernet (Wired)";
            case NetworkInterfaceType.Wireless80211:
                return "Wireless (Wi-Fi)";
            case NetworkInterfaceType.Ppp:
                return "Point-to-Point (Dial-up/VPN)";
            case NetworkInterfaceType.Loopback:
                return "Loopback";
            case NetworkInterfaceType.Tunnel:
                return "Tunnel";
            case NetworkInterfaceType.HighPerformanceSerialBus:
                return "IEEE 1394 (FireWire)";
            default:
                return type.ToString();
        }
    }

    // 6. DNS and gateway information
    public static void GetDNSAndGatewayInfo()
    {
        Console.WriteLine("\n=== DNS and Gateway Information ===");

        NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces()
            .Where(i => i.OperationalStatus == OperationalStatus.Up)
            .ToArray();

        foreach (NetworkInterface adapter in interfaces)
        {
            Console.WriteLine($"\nAdapter: {adapter.Name}");

            IPInterfaceProperties properties = adapter.GetIPProperties();

            // DNS servers
            Console.WriteLine("  DNS Servers:");
            foreach (IPAddress dns in properties.DnsAddresses)
            {
                Console.WriteLine($"    {dns}");
                TestDNSResponse(dns);
            }

            // Gateway addresses
            GatewayIPAddressInformationCollection gateways = properties.GatewayAddresses;
            if (gateways.Count > 0)
            {
                Console.WriteLine("  Gateway:");
                foreach (GatewayIPAddressInformation gateway in gateways)
                {
                    Console.WriteLine($"    {gateway.Address}");
                }
            }

            // WINS servers (if configured)
            if (properties.WinsServersAddresses.Count > 0)
            {
                Console.WriteLine("  WINS Servers:");
                foreach (IPAddress wins in properties.WinsServersAddresses)
                {
                    Console.WriteLine($"    {wins}");
                }
            }
        }
    }

    private static async void TestDNSResponse(IPAddress dnsServer)
    {
        try
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            using (var ping = new Ping())
            {
                PingReply reply = await ping.SendPingAsync(dnsServer, 1000);
                stopwatch.Stop();

                if (reply.Status == IPStatus.Success)
                {
                    Console.WriteLine($"      ✓ Responds in {stopwatch.ElapsedMilliseconds}ms");
                }
                else
                {
                    Console.WriteLine($"      ✗ No response");
                }
            }
        }
        catch
        {
            Console.WriteLine($"      ✗ Unable to test");
        }
    }

    // 7. Port scanning and connection testing
    public static async Task TestCommonPorts(string host = "localhost")
    {
        Console.WriteLine($"\n=== Common Port Test for {host} ===");

        Dictionary<int, string> commonPorts = new Dictionary<int, string>
        {
            { 21, "FTP" },
            { 22, "SSH" },
            { 23, "Telnet" },
            { 25, "SMTP" },
            { 53, "DNS" },
            { 80, "HTTP" },
            { 110, "POP3" },
            { 143, "IMAP" },
            { 443, "HTTPS" },
            { 993, "IMAPS" },
            { 995, "POP3S" },
            { 3389, "RDP" },
            { 5432, "PostgreSQL" },
            { 3306, "MySQL" },
            { 1433, "SQL Server" },
            { 8080, "HTTP Alternate" }
        };

        foreach (var port in commonPorts)
        {
            Console.Write($"Testing {port.Value} (port {port.Key})... ");

            try
            {
                using (var tcpClient = new System.Net.Sockets.TcpClient())
                {
                    Stopwatch stopwatch = Stopwatch.StartNew();
                    var connectTask = tcpClient.ConnectAsync(host, port.Key);

                    if (await Task.WhenAny(connectTask, Task.Delay(1000)) == connectTask)
                    {
                        stopwatch.Stop();
                        Console.WriteLine($"✓ Open ({stopwatch.ElapsedMilliseconds}ms)");
                    }
                    else
                    {
                        Console.WriteLine("✗ Closed/Filtered");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error: {ex.Message}");
            }
        }
    }

    // Helper class for network events
    private class NetworkEvent
    {
        public string Timestamp { get; set; }
        public string EventType { get; set; }
        public bool NetworkAvailable { get; set; }
        public string Message { get; set; }
    }

    // Main method
    static void Main(string[] args)
    {
        Console.WriteLine("=== C# Network Status Monitor ===\n");

        try
        {
            // Run all network monitoring examples
            CheckNetworkAvailability();

            Console.WriteLine("\nTesting Internet Connectivity...");
            TestInternetConnectivity().GetAwaiter().GetResult();

            MonitorNetworkBandwidth();

            DetectConnectionTypes();

            GetDNSAndGatewayInfo();

            Console.WriteLine("\nTesting Common Ports...");
            TestCommonPorts().GetAwaiter().GetResult();

            Console.WriteLine("\nPress Enter to start network event monitoring...");
            Console.ReadLine();

            StartNetworkEventMonitoring();

            Console.WriteLine("\nNetwork monitoring examples completed!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error in network monitoring: {ex.Message}");
        }
    }
}