'How to elevate my winform privileges (at runtime) to admin on button press
I am developing an application that should not require elevated privileges unless the user wants to change a network adapter's IP address. I would like to allow the application to run as invoked however require and maintain elevated privileges after a button is pressed.
With that said, my ElevateProcess() is getting the following exception: Process was not started by this object, so requested information cannot be determined.
My question is: how do I elevate "this" (already running) winform application to admin on a button press.

private void submitIPChangesBtn_Click(object sender, EventArgs e)
{
GeneralHelper.ElevateProcess();
HelperNetwork.setIP("192.168.0.23", "255.255.255.0");
}
Elevate process function:
public static Process ElevateProcess()
{
Process source = Process.GetCurrentProcess();
//Create a new process
Process target = new Process();
target.StartInfo = source.StartInfo;
target.StartInfo.FileName = source.MainModule.FileName;
target.StartInfo.WorkingDirectory = Path.GetDirectoryName(source.MainModule.FileName);
//Required for UAC to work
target.StartInfo.UseShellExecute = true;
target.StartInfo.Verb = "runas";
try
{
if (!target.Start())
return null;
}
catch (Win32Exception e)
{
//Cancelled
if (e.NativeErrorCode == 1223)
return null;
throw;
};
return target;
}
Solution 1:[1]
I am not sure I like this solution (as it may become more complicated as other parts of the application may be pending and just killing the application is less than ideal.
With that said, what I did was pass arguments into the ElevateProcess(...) function and when the process is successfully launched with admin privileges the new process will have to parse the arguments and act on them accordingly. Additionally, to prevent the exception I just needed to comment out the line:
target.StartInfo = source.StartInfo;
Again, I am not a huge fan of needing to kill the current process and starting a one. If there is any way to bring the current process to admin, I would greatly appreciate the recommendation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JCoder |

