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;
}