Thursday, August 6, 2009

Dealing with UAC

What happens if your application wants to update itself, or change files which UAC will not allow you to update without elevation. The solution is to not elevate your whole application. This would defeat the purpose of UAC in the first place.

One solution is to create a new project in VS, which might be a console app that you run invisibly for instance. The console app will do some file copying or whatever else needs UAC elevation and that is all. Right click the new UAC project you have created and add an 'application manifest file'.

Make sure this is in the manifest file,

<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>

And you will be away. So back to your unelevated program, calling this console app from your unelevated code can be done like this. What this will do when you call process.Start() is prompt for UAC elevation,

Process process = new Process();
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Exited += new EventHandler(process_Exited);

I have left most of it out, but the important thing there is that I have said it should have no window, and the style should be hidden. I have also defined an exit event so that I can pick up when the UAC app has finished.

No comments: