How to force a WPF application to run in Administrator mode
Asked Answered
S

6

59

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?

Samellasameness answered 11/3, 2011 at 18:8 Comment(0)
H
92

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.

Hogue answered 11/3, 2011 at 18:19 Comment(10)
Will this work on Windows 7 as well? There is a note on that page that brings up this question... In future releases, the only way to run an application elevated will be to have a signed application manifest that identifies the privilege level that the application needs.Lycaonia
@kzen, as of now - yes - this same procedure will work for Windows 7.Hogue
Will this work if I install my application on Windows Server 2008 machines, that is where I am issues with running my application?Samellasameness
VCSJones, I tried adding {MyAppliationName}.exe.Manifest file to the project and when I compile I get an error which seems very common. Error is "ClickOnce does not support the request execution level 'requireAdministrator'."Samellasameness
Is your application XBAP or ClickOnce deployed?Hogue
Thanks VCSJones. Your solution worked for me. I had to disable ClickOnce to get rid of that error. I did this by going to project properties, security tab and unchecking the "Enable ClickOnce security settings" option.Samellasameness
When I select the View UAC Settings (app.manifest) and change <requestedExecutionLevel level="asInvoker" uiAccess="false" /> to <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> I get an error stating "Error 6 ClickOnce does not support the request execution level 'requireAdministrator'. " this is accurate according to MSDN.Advocacy
@Michael, ClickOnce doesn't directly support a manifest that can start as an administrator. If you need a clickOnce app to run as an Admin, you should write a bootstrap program to start the other as elevated.Hogue
@Hogue I have the found several examples of the hack around WPF, I was actually hoping for something that didn't require the user to approve running as an administrator. Thanks for the reply!Advocacy
Can this be used in VS2013 Express? We don't seem to have any deployment method other than ClickOnce.Lent
K
33
  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.

Kizzee answered 22/11, 2018 at 13:24 Comment(1)
Working fine. :)Cabby
I
5

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.
Incandesce answered 17/2, 2020 at 12:20 Comment(2)
What if step 2 doesn't have App.Manifest to select? I don't know what's going on with my project but I really don't have manifest file to select using visual studio 2019 with WPF c#Ulysses
@NorynBasaya It's there for me, it's named 'Application Manifest File'.Mere
S
4

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

Sprawl answered 12/8, 2018 at 1:37 Comment(1)
That was the only solution without breaking the ClickOne sign and security. if you want to use publish that the solution.Selfinsurance
E
2

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)
                {
                }
            }
        }
}
Eeg answered 11/11, 2021 at 9:55 Comment(0)
T
0

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

    }

}
Transubstantiate answered 7/7, 2023 at 14:54 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.