SVI
SVI

Reputation: 1651

How to force a WPF application to run in Administrator mode

I have an WPF application which access windows services, task schedulers on the local machine. When I deploy this WPF application and run it without "Run as Administrator" , it fails as it is not able to access the windows services and task schedulers on the local machine. If I run it with "Run as Administrator", it works correctly.

How do I make my application by default run in admin mode when it is deployed in production?

Upvotes: 60

Views: 51850

Answers (6)

Eng.Mohamed Bassuny
Eng.Mohamed Bassuny

Reputation: 21

I found this code helping me to do it in the right way I want.

I want the app run "By the USER choois as administrator" not making the app itself run itself as administrator.

This method forces the user to run the app as administrator

So this is my code at last

public partial class App : Application
{
    public static bool IsUserAdministrator()
    {
        try
        {
            WindowsIdentity user = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(user);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }
        catch
        {
            return false;
        }
    }

    protected override void OnStartup(StartupEventArgs e)
    {

        if (!IsUserAdministrator())
        {

            //TODO if NOT RUN As Adminstrator By the USER Chooise

            System.Windows.Forms.MessageBox.Show("not admin");
            Application.Current.Shutdown();
        }
        else
        {
            //TODO if RUN As Adminstrator By the USER Chooise

            System.Windows.Forms.MessageBox.Show("Admin");
        }

    }

}

Upvotes: 0

Sandeep Jadhav
Sandeep Jadhav

Reputation: 928

WPF App.xaml.cs
Current application process will kill and same application with new process as run as administrator will going to launch.

public partial class App : Application
{
        //This function will be called on startup of the applications
        protected override void OnStartup(StartupEventArgs e)
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);

            if (principal.IsInRole(WindowsBuiltInRole.Administrator) == false && principal.IsInRole(WindowsBuiltInRole.User) == true)
            {
                ProcessStartInfo objProcessInfo = new ProcessStartInfo();
                objProcessInfo.UseShellExecute = true;
                objProcessInfo.FileName = Assembly.GetEntryAssembly().CodeBase;
                objProcessInfo.UseShellExecute = true;
                objProcessInfo.Verb = "runas";
                try
                {
                    Process proc = Process.Start(objProcessInfo);
                    Application.Current.Shutdown();
                }
                catch (Exception ex)
                {
                }
            }
        }
}

Upvotes: 2

Maghalakshmi Saravana
Maghalakshmi Saravana

Reputation: 813

Steps to Make the WPF application to Run in Administrator Mode

1.Open the Solution Explorer

2.Right CLick on the solution--->Add---->New Item---->App.Manifest---->OK

3.Edit the Manifest file as follows:

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

(TO)

 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

4.After editing the Manifest file,Goto Solution project(RightCLick)------>properties------->Security

Turn out the Checkbox of "Enable ClickOnce Security Settings"

  1. Run the Application, and Take setup, Now the application with Run as Administrator mode is acheived.

Upvotes: 5

SLdragon
SLdragon

Reputation: 1627

  1. Right-click your WPF project to add new Item: "Add->New Item..."
  2. Select "Application Manifest File" and click Add
  3. Double Click your newly created manifest file and change the
<requestedExecutionLevel level="asInvoker" uiAccess="false" />

to

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Then the WPF application would run as Administrator.

Upvotes: 36

M&#229;rsh&#229;ll
M&#229;rsh&#229;ll

Reputation: 138

If you don't want broke the Clickonce this code is the best solution:

using System.Security.Principal;
using System.Management;
using System.Diagnostics;
using System.Reflection;
//Put this code in the main entry point for the application
// Check if user is NOT admin 
if (!IsRunningAsAdministrator())
{
    // Setting up start info of the new process of the same application
    ProcessStartInfo processStartInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().CodeBase);

    // Using operating shell and setting the ProcessStartInfo.Verb to “runas” will let it run as admin
    processStartInfo.UseShellExecute = true;
    processStartInfo.Verb = "runas";

    // Start the application as new process
    Process.Start(processStartInfo);

    // Shut down the current (old) process
    System.Windows.Forms.Application.Exit();
    }
}

/// <summary>
/// Function that check's if current user is in Aministrator role
/// </summary>
/// <returns></returns>
public static bool IsRunningAsAdministrator()
{
    // Get current Windows user
    WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();

    // Get current Windows user principal
    WindowsPrincipal windowsPrincipal = new WindowsPrincipal(windowsIdentity);

    // Return TRUE if user is in role "Administrator"
    return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
}

Founded in: http://matijabozicevic.com/blog/wpf-winforms-development/running-a-clickonce-application-as-administrator-also-for-windows-8

Upvotes: 4

vcsjones
vcsjones

Reputation: 141638

You need to add an app.manifest. Change the requestedExecutionLevel from asInvoker to requireAdministrator. You can create a new manifest by using the add file dialog, change it to require administrator. Make sure that your project settings are set to use that manifest as well. This will allow you to simply double click the application and it will automatically prompt for elevation if it isn't already.

See here for more documentation:

http://msdn.microsoft.com/en-us/library/bb756929.aspx

EDIT: For what it's worth, the article uses VS 2005 and using mt.exe to embed the manifest. if you are using Visual studio 2008+, this is built in. Simply open the properties of your Project, and on the "Application" tab you can select the manifest.

Upvotes: 92

Related Questions