1

I have a winform application with the following code in Program.cs to make sure my app is always running with administrative privilege:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // Init visual styles
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        // Check if app is launched with administrative privilage
        WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);

        // Check if application is already running
        bool mutexCheck;
        var mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetType().GUID.ToString(), out mutexCheck);
        if (!mutexCheck)
        {
            // Error
            Utils.ShowError("Program is already running.");
            return;
        }

        // If app is running without administrative privilage
        if (!administrativeMode)
        {
            // Request administrative privilage
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.Verb = "runas";
            startInfo.FileName = Application.ExecutablePath;
            try
            {
                // Run app as administrator
                Process.Start(startInfo);
            }
            catch (Exception ex)
            {
                // Error
                Utils.ShowError("Program failed to start - " + ex.Message);
                return;
            }
        }
        return;

        // Launch application
        Application.Run(new MyApp());
        GC.KeepAlive(mutex);
    }
}

Every time I press F5 to run the app in debug mode in Visual Studio 2015, the app appears to be just running - the debug environment is not launching.

So, what I have to do is go to Debug -> Attach to Process... and select MyApp.exe and then I am prompted with this window:

enter image description here

Then when I click on Restart under different credentials - VS2015 restarts. I will then have to close the already running instance of MyApp and then press F5 to re-launch with elevated privilege; when I do - the debug works.

Is there a way to set my VS2015 to always run this project with elevated privilege?

Latheesan
  • 23,247
  • 32
  • 107
  • 201

1 Answers1

2

Try running your Visual Studio as Administrator. In the cases that I faced with insufficient privileges Running Visual Studio As Administrator has fixed my problem.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • 1
    I have achieved this by following the steps outlined here http://stackoverflow.com/a/9654880/2332336 for `Windows 8 and 8.1` (I am on Windows 10 and this works). Now I can just launch the project solution file and it automatically launches VS2015 with admin rights :) – Latheesan Aug 29 '15 at 15:10