Connecting to local network from inside my own app

50 Views Asked by At

I have this wpf app, that should later be something like a kiosk... Now in my settings page I have the WiFi settings. I have managed to display all local networks and I can connect and disconnect from the ones that are not password protected. But I can't connect to the ones that have password protection, even for example if I know password of that network... Similar to Windows WiFi settings when you type in password and connect. All in all I just need to trigger that connection in windows not actually inside the app. All I get is error message saying failed to connect to network.




namespace WPFDemo.pages
{

    public partial class SettingsPage : UserControl
    {

        

        private Dictionary<string, bool> networkConnectionStatus = new Dictionary<string, bool>();


        public SettingsPage()

        {
            InitializeComponent();
            
        }


        //Wi-Fi Function 
        private void TestToggleButton_Click(object sender, RoutedEventArgs e)
        {
            
            string ssid = "Alfa ProTeh";

            // Check current connection status
            if (IsConnectedToSSID(ssid))
            {
                // If connected, disconnect
                DisconnectFromWiFi();
            }
            else
            {
                // If not connected, try to connect
                ConnectToWiFi(ssid);
            }
        }
        private bool IsConnectedToSSID(string ssid)
        {
            // Use netsh to check the current connected WiFi SSID
            Process process = new Process();
            process.StartInfo.FileName = "netsh";
            process.StartInfo.Arguments = "wlan show interfaces";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();

            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            // This is a simple check; consider more robust parsing for real applications
            return output.Contains(ssid);
        }
        private void DisconnectFromWiFi()
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", "wlan disconnect")
            {
                CreateNoWindow = true,
                UseShellExecute = false
            };

            Process process = Process.Start(processStartInfo);
            process.WaitForExit();


        }
        private void ConnectToWiFi(string ssid, string password = null)
        {
            string commandArguments = password == null ?
                $"wlan connect name=\"{ssid}\" ssid=\"{ssid}\"" :
                $"wlan connect name=\"{ssid}\" ssid=\"{ssid}\" key=\"{password}\""; // Note: The actual netsh command might differ for providing the password

            ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", commandArguments)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            Process process = new Process();
            process.StartInfo = processStartInfo;
            process.Start();
            process.WaitForExit();

            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();

            if (process.ExitCode == 0)
            {
                MessageBox.Show("Connected successfully to " + ssid, "Success", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                MessageBox.Show("Failed to connect to " + ssid + ".\nError: " + error, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {
            wifiNetworksList.Items.Clear(); // Clear existing items

            ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", "wlan show networks")
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true
            };

            using (Process process = new Process())
            {
                process.StartInfo = processStartInfo;
                process.Start();

                while (!process.StandardOutput.EndOfStream)
                {
                    string line = process.StandardOutput.ReadLine();
                    // Simple parsing based on the output format of netsh
                    if (line.Contains("SSID"))
                    {
                        string networkName = line.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
                        // Assume all networks are secured for this example
                        var isConnected = IsConnectedToSSID(networkName);
                        var buttonText = isConnected ? "Disconnect" : "Connect";
                        networkConnectionStatus[networkName] = isConnected; // Update your dictionary accordingly

                        var connectButton = new Button
                        {
                            Content = buttonText,
                            Tag = networkName,
                            Margin = new Thickness(5),
                        };
                        connectButton.Click += ConnectToNetwork_Click;

                        var passwordTextBox = new TextBox
                        {
                            Width = 120,
                            Margin = new Thickness(5),
                            Tag = networkName, // Use Tag to identify the network
                        };

                        var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };
                        stackPanel.Children.Add(new TextBlock { Text = networkName, VerticalAlignment = VerticalAlignment.Center });
                        stackPanel.Children.Add(passwordTextBox);
                        stackPanel.Children.Add(connectButton);

                        var listBoxItem = new ListBoxItem();
                        listBoxItem.Content = stackPanel;
                        wifiNetworksList.Items.Add(listBoxItem);
                    }
                }
            }
        }
        private void scrollViewer_MouseWheel(object sender, MouseWheelEventArgs e)
        {

        }
        private void ConnectToNetwork_Click(object sender, RoutedEventArgs e)
        {
            Button connectButton = sender as Button;
            if (connectButton != null)
            {
                string networkName = connectButton.Tag.ToString();
                var passwordBox = ((StackPanel)connectButton.Parent).Children.OfType<TextBox>().FirstOrDefault(tb => tb.Tag.ToString() == networkName);

                if (connectButton.Content.ToString() == "Connect")
                {
                    string password = passwordBox?.Text;
                    ConnectToWiFi(networkName, password);
                    connectButton.Content = "Disconnect";
                    wifiToggleButton.IsChecked = true;
                }
                else
                {
                    DisconnectFromWiFi();
                    connectButton.Content = "Connect";
                    wifiToggleButton.IsChecked = false;
                }
            }
        }
        //Wi-Fi Function end 

    }
}
0

There are 0 best solutions below