1

How I can run below command under administrator approval in visual c#? Also I need to hide console windows while running console.

Thanks.

private void button5_Click(object sender, EventArgs e)
    {            
        Process process = new Process();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = "/C netsh wlan set hostednetwork mode=allow ssid=HotSpot key=12345678";
        startInfo.Verb = "runas";
        startInfo.UseShellExecute = true;
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo = startInfo;
        process.Start();

        Process wifiStart = new Process();
        ProcessStartInfo wifiStartInfo = new ProcessStartInfo();
        wifiStartInfo.FileName = "netsh.exe";
        wifiStartInfo.Arguments = "/C wlan start hostednetwork";
        wifiStartInfo.Verb = "runas";
        wifiStartInfo.UseShellExecute = true;
        wifiStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        process.StartInfo = wifiStartInfo;
        wifiStart.Start();
    }
user3782130
  • 31
  • 1
  • 4

1 Answers1

4
Process.Start(new ProcessStartInfo {
    FileName = "netsh",
    Arguments = "wlan set hostednetwork mode=allow ssid=HotSpot key=12345678",
    Verb = "runas",
    UseShellExecute = true,
    WindowStyle = ProcessWindowStyle.Hidden
});

This starts a process using the "runas" verb, which makes the shell try to execute it in elevated privileges mode. But we actually need the shell to be involved in this in the first place, hence the UseShellExecute = true value.

The last property tells the shell to hide the new process' window, but I'm not sure this will work for a console program.

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158