C# — Как программно отключить Wi-Fi в Windows 8 10

Я пишу приложение, отключающее WiFi. Этого нельзя сделать, отключив сетевой адаптер с помощью WMI или вызвав netsh и т. д. Для Windows 10 у меня работает следующий код. Как сделать то же самое для Windows 8?

using Windows.Devices.Radios;

public async void TurnWifiOff()
{
    await Radio.RequestAccessAsync();
    var radios = await Radio.GetRadiosAsync();

    foreach (var radio in radios)
    {
        if (radio.Kind == RadioKind.WiFi)
        {
            await radio.SetStateAsync(RadioState.Off);
        }
    }
}

person Bednarus3    schedule 11.09.2019    source источник
comment
Вы должны использовать WlanSetInterface с опкодом wlan_intf_opcode_radio_state.   -  person Mike Petrichenko    schedule 11.09.2019


Ответы (1)


Майк Петриченко, спасибо за подсказку. Я нашел решение, основанное на «wlanapi.dll», предоставленном CodePlex: https://archive.codeplex.com/?p=managedwifi После добавления в проект двух файлов «Interop.cs» и «WlanApi.cs» следующий код выполнил свою работу.

using NativeWifi;
using System.Runtime.InteropServices;

{

    WlanClient client = new WlanClient();
    foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
    {
        IntPtr radioStatePtr = new IntPtr(0L);
        try
        {
            Wlan.WlanPhyRadioState radioState = new Wlan.WlanPhyRadioState();
            radioState.dwPhyIndex = 0;
            radioState.dot11HardwareRadioState = Wlan.Dot11RadioState.On;
            radioState.dot11SoftwareRadioState = Wlan.Dot11RadioState.Off; //In this place we set WiFi to be enabled or disabled

            radioStatePtr = Marshal.AllocHGlobal(Marshal.SizeOf(radioState));
            Marshal.StructureToPtr(radioState, radioStatePtr, false);

            Wlan.ThrowIfError(
                Wlan.WlanSetInterface(
                            client.clientHandle,
                            wlanIface.InterfaceGuid,
                            Wlan.WlanIntfOpcode.RadioState,
                            (uint)Marshal.SizeOf(typeof(Wlan.WlanPhyRadioState)),
                            radioStatePtr,
                            IntPtr.Zero));
        }
        finally
        {
            if (radioStatePtr.ToInt64() != 0)
                Marshal.FreeHGlobal(radioStatePtr);
        }
    }
}
person Bednarus3    schedule 12.09.2019