Reputation: 48736
The other day, I came across an application that when you run it, it comes up with the UAC screen and requests to be run with administrator privileges. Clicking 'Yes' on the UAC screen runs the application like normal. The interesting thing is that if you click 'No', the application, instead of exiting, still runs, but runs in a limited user account (with less functionality, of course).
My question is, how can I configure my C# application to do this? I know my application can have an application manifest to run in elevated privileges, but how do I duplicate the kind of behavior I just explained above?
Upvotes: 2
Views: 491
Reputation: 11878
You can keep all the code in one application. The application manifest does not request the application to be run elevated, it uses asInvoker
level.
When the application is started, it tries to re-start itself elevated. I mean it starts another process with runas
verb. If it succeeds, then the first instance just exists.
If elevation was not successful, then it continues to run with limited functionality.
But think about the user experience:
Not everyone in the world works as administrator. For them, elevation would not look as clicking Continue
button, the UAC will ask them to provide user name and password of an administrator.
From this point of view, Microsoft recommended approach works great: run as regular user until you really need to elevate. All elevation points should be clearly marked in the UI. You can still use the same exe file to run non-elevated and elevated instances, yet you must implement a communication mechanism so the non-elevated instance can provide all the data to perform the operation requested by the user. Once you started elevated instance, you can keep it running and exit the non-elevated one, so that other operations could be performed without elevation.
Thus it means more effort, but a much better user experience.
Upvotes: 0
Reputation: 35869
To do this with a different elevated application you can use a "launcher" (or the launcher is the "normal" app).
If you wanted three applications you might have a WinForms launcher something like:
[STAThread]
static void Main()
{
const int ERROR_CANCELLED = 1223;
try
{
Process.Start("el.exe");
// ran el in elevated node...
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode == ERROR_CANCELLED)
{
Process.Start("normal.exe");
}
}
}
If you were doing two applications, you could do something like:
[STAThread]
static void Main()
{
const int ERROR_CANCELLED = 1223;
try
{
Process.Start("el.exe");
// ran el in elevated node...
}
catch (Win32Exception ex)
{
if (ex.NativeErrorCode == ERROR_CANCELLED)
{
// "continue" as un-elevated app.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Upvotes: 1