views:

31

answers:

2

I am in the process of developing an application which uses a legacy USB driver. For some reason the developers of the legacy USB driver decided to write information to the registry and this process requires me to have administrative privileges for my application.

Now, the USB functionality that uses the registry should be only done by a user once, or when he wants to recalibrate his device so I don't need administrative privileges all the time.

When you want to debug an application which requires administrative privileges from Visual Studio you get a pop-up with a request to restart the application with the correct credentials. How can I make that myself? I want to start my application normally, but when the user goes to the calibration menu I want to present him with a similar pop-up telling him that for this option he has to restart the application with administrative privileges.

+1  A: 

You can ask a program to start up with Admin privileges by using the ProcessStartInfo type and setting the Verb property to "runas".

var info = new ProcessStartInfo();
info.UseShellExecute = true;
info.Verb = "runas";
// set the rest of the information
Process.Start(info);

This will prompt the user with the standard Windows dialog for running admin code.

JaredPar
Thanks. Combining this with the other answer I can do what I want.
tyfius
+1  A: 

Visual Studio doesn't restart itself as admin, it just detects whether it's running as admin or not and if not, puts up a message box. Simplest test for you would be to call IsInRole - even when you're in the Administrators group, if the app is running non elevated it returns false. For example:

        WindowsIdentity wi = WindowsIdentity.GetCurrent();
        WindowsPrincipal wp = new WindowsPrincipal(wi);

        if (wp.IsInRole("Administrators"))
        {
            MessageBox.Show("Yes, you are an Administrator.", "Is Administrator?", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        else
        {
            MessageBox.Show("No, you are not an Administrator.", "Is Administrator?", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Rather than these message boxes, you could put your own about "please close and restart me". Or if you want to show off, give them a button to click that will launch an elevated instance (using ProcessStart and runas) and close this one.

Kate Gregory