Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Admin rights prompt popup in C# application

Tags:

c#

uac

wpf

c#-3.0

I have a function in my application which requires admin rights.

What I want is when I click the button to execute that function, it should ask for admin username and password. (Launch UAC dialog. Also show icon on that button.)

Is it possible?

alt text

PS: I know about launching the application with admin right by making modifications in manifest file.

Also this function is a part of a large program and it cannot be transferred to a separate program.

like image 275
Raj Avatar asked Nov 03 '10 08:11

Raj


2 Answers

You can get the icon using StockIcons.Shield from the Windows API Code Pack

You can run a program with admin privileges without changing the program manifest using the "runas" verb (you can also use this to re-launch your program with admin rights):

Process.Start(new ProcessStartInfo()
   {
        Verb = "runas",
        FileName = "Notepad.exe",
   });

There is a COM API that let you create a COM object with admin rights inside a non-admin process, but I believe it's very difficult to use this from a .net application.

like image 97
Nir Avatar answered Sep 21 '22 17:09

Nir


The best way to achieve this is to have a secondary executable that contains the code that requires administrative rights, which is manifested appropriately. When your application needs to execute the code that requires administrative rights, call that program.

For example:

MyProgram.exe - no manifest
MyProgramElevated.exe - has a manifest that indicates it requires admin rights

When MyProgram.exe needs to perform an action as elevated it executes MyProgramElevated.exe, passing command line parameters indicating what elevated task is required.

like image 28
Rob Avatar answered Sep 18 '22 17:09

Rob