2

I have a WPF app that has a control(checkbox /toggle switch) . I want to turn Wi-Fi On/Off by using those buttons. I have tried the following code but it doesnt seem to help

I am using Windows 10 and Visual Studio 2015

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication4
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // string name = "Hello World";
        }


        static void Enable(string interfaceName)
        {
            System.Diagnostics.ProcessStartInfo psi =
                   new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo = psi;
            p.Start();
        }

        static void Disable(string interfaceName)
        {
            System.Diagnostics.ProcessStartInfo psi =
                new System.Diagnostics.ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo = psi;
            p.Start();
        }

        private void checkBox_Checked(object sender, RoutedEventArgs e)
        {
            string interfaceName = "Local Area Connection";

            Disable(interfaceName);


        }

    }
}

I went through the following link with the first answer but there is no help .

I need some help so that I can programatically turn off/On Wi-Fi with the click of a button.

Community
  • 1
  • 1
Apoorv
  • 2,023
  • 1
  • 19
  • 42
  • Are you sure you dont need an elevated command prompt (admin rights) to enable/disable interfaces? Im pretty sure you need to be administrator to do this. Your link even states this. – CSharpie Dec 24 '15 at 10:56
  • Possible duplicate of [How to disable/enable network connection in c#](http://stackoverflow.com/questions/172875/how-to-disable-enable-network-connection-in-c-sharp) – CSharpie Dec 24 '15 at 10:58
  • can you tell me the process of having admin rights? I started Visual Studio as an administrator ? any other method ? – Apoorv Dec 24 '15 at 11:42
  • Just search for it here... – CSharpie Dec 24 '15 at 13:20

2 Answers2

2

You can turn on/off Wi-Fi by changing software radio state (not hardware radio state) by Native Wifi API. Using some codes of Managed Wifi API project, I wrote a sample.

using System;
using System.Linq;
using System.Runtime.InteropServices;
using NativeWifi;

public static class WlanRadio
{
    public static string[] GetInterfaceNames()
    {
        using (var client = new WlanClient())
        {
            return client.Interfaces.Select(x => x.InterfaceName).ToArray();
        }
    }

    public static bool TurnOn(string interfaceName)
    {
        var interfaceGuid = GetInterfaceGuid(interfaceName);
        if (!interfaceGuid.HasValue)
            return false;

        return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.On);
    }

    public static bool TurnOff(string interfaceName)
    {
        var interfaceGuid = GetInterfaceGuid(interfaceName);
        if (!interfaceGuid.HasValue)
            return false;

        return SetRadioState(interfaceGuid.Value, Wlan.Dot11RadioState.Off);
    }

    private static Guid? GetInterfaceGuid(string interfaceName)
    {
        using (var client = new WlanClient())
        {
            return client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName)?.InterfaceGuid;
        }
    }

    private static bool SetRadioState(Guid interfaceGuid, Wlan.Dot11RadioState radioState)
    {
        var state = new Wlan.WlanPhyRadioState
        {
            dwPhyIndex = (int)Wlan.Dot11PhyType.Any,
            dot11SoftwareRadioState = radioState,
        };
        var size = Marshal.SizeOf(state);

        var pointer = IntPtr.Zero;
        try
        {
            pointer = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(state, pointer, false);

            var clientHandle = IntPtr.Zero;
            try
            {
                uint negotiatedVersion;
                var result = Wlan.WlanOpenHandle(
                    Wlan.WLAN_CLIENT_VERSION_LONGHORN,
                    IntPtr.Zero,
                    out negotiatedVersion,
                    out clientHandle);
                if (result != 0)
                    return false;

                result = Wlan.WlanSetInterface(
                    clientHandle,
                    interfaceGuid,
                    Wlan.WlanIntfOpcode.RadioState,
                    (uint)size,
                    pointer,
                    IntPtr.Zero);

                return (result == 0);
            }
            finally
            {
                Wlan.WlanCloseHandle(
                    clientHandle,
                    IntPtr.Zero);
            }
        }
        finally
        {
            Marshal.FreeHGlobal(pointer);
        }
    }

    public static string[] GetAvailableNetworkProfileNames(string interfaceName)
    {
        using (var client = new WlanClient())
        {
            var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
            if (wlanInterface == null)
                return Array.Empty<string>();

            return wlanInterface.GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags.IncludeAllManualHiddenProfiles)
                .Select(x => x.profileName)
                .Where(x => !string.IsNullOrEmpty(x))
                .ToArray();
        }
    }

    public static void ConnectNetwork(string interfaceName, string profileName)
    {
        using (var client = new WlanClient())
        {
            var wlanInterface = client.Interfaces.FirstOrDefault(x => x.InterfaceName == interfaceName);
            if (wlanInterface == null)
                return;

            wlanInterface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
        }
    }
}

Check available interface names by GetInterfaceNames and then call TurnOn/TurnOff with one of the names. According to MSDN, it should require administrator priviledge but it doesn't on my environment.


SUPPLEMENT

I added two more methods to this class. So the sequence will be something like this.

  1. Get existing Wi-Fi interface names by GetInterfaceNames.
  2. Select an interface and turn it on by TurnOn.
  3. Get profile names associated to available Wi-Fi networks through the interface by GetAvailableNetworkProfileNames.
  4. Select a profile and connect to the network by ConnectNetwork.
  5. After finished using the network, turn the interface off by TurnOff.
emoacht
  • 2,764
  • 1
  • 13
  • 24
  • Hi , would it be possible for you to upload the complete source code as i am unable to add NativeWiFi namespace . I have tried the ManagedWiFi but doesnt seem to help – Apoorv Dec 28 '15 at 07:14
  • @Apoorv If you downloaded Managed Wifi API source code from "DOWNLOADS" section, it's old one. Try "Download" link in "SOURCE CODE" section to get new one. And since its target framework is very old 2.0, you will need to change it to the latest. – emoacht Dec 28 '15 at 10:57
  • Thanks . I have done that.Now I see that the MangedWiFi has 2 projects-ManagedWiFi & WiFi Example . tell me where to add these classes you mentioned above – Apoorv Dec 28 '15 at 12:39
  • I have done something.When I am calling the TurnOff method , It is asking for interfaceName . From where shall I get InterfaceName ? – Apoorv Dec 28 '15 at 12:45
  • @Apoorv Add the class to WifiExample project. To get interface names, call GetInterfaceNames method. If successful, it will return array of available interface names. – emoacht Dec 28 '15 at 14:24
  • I have added the steps into a WPF project I am getting error that system.Linq not found. it seems that the DLL is not there under Add Reference – Apoorv Jan 13 '16 at 10:30
  • Oh there was some version mismatch ! It seems working now . I have added the class. What is the next step? shall I add a WPF Window or a new project inside the main project to access the features? – Apoorv Jan 13 '16 at 11:11
  • thanks for your prompt response. Now I have added the code in a class file , added a Form and calling the Static Class to get the interface name. Is this the correct approach? – Apoorv Jan 13 '16 at 11:19
  • To try and check if it will work, maybe cleaning up the content of Main method of console app and calling the methods of this class from Main method will be enough. – emoacht Jan 13 '16 at 11:38
  • I see something here ! What I see is that without adding the class you mentioned above ,when I ran the application , It rebooted my WiFi and reconnected it. This is also what I want . my requirements are rebooting and then turning Off/ On that too from a WPF application. Do u suggest a way ? – Apoorv Jan 13 '16 at 11:40
  • ok . I made it to run somehow. but I need your help . I will mark this as an answer now ! I need your help in the code – Apoorv Jan 13 '16 at 11:49
  • What do you mean by "reboot" WiFi? – emoacht Jan 13 '16 at 21:45
  • Restart the Wi-Fi . the Wi-Fi should disconnect and connect again ! – Apoorv Jan 14 '16 at 05:41
  • Is there a way to get to know on what Band the WiFi is connected and is it possible to switch to the other band ? – Apoorv Apr 04 '16 at 09:26
  • @emoacht Is it possible to toggle wifi? – User not found Feb 07 '22 at 19:11
0

You could use the device library from windows universal apps.

Documentation: https://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.wifi.aspx

Microsoft sample: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples

In order to use this library with WPF application you could add

< TargetPlatformVersion > 8.0< / TargetPlatformVersion >

to your .csproj file between

< PropertyGroup>.... < /PropertyGroup>

  • The guide for adding the library https://software.intel.com/en-us/articles/using-winrt-apis-from-desktop-applications – Emil Bolet Dec 24 '15 at 15:33
  • I am using Windows 10 and Visual Studio 2015 . As stated I want to turn off Wi-Fi Programatically ! How can the above answer help me? – Apoorv Dec 24 '15 at 19:12