Freigeben über


How to programmatically determine whether UAC is enabled or not

The moth says,

This is a question I get often:

"How can I determine if User Account Control is on or off via code?"

The answer I always give:

"You are asking the wrong question. Who cares?"

The point being that, regardless of whether the user has turned off UAC or not, your application should still be partitioned and work correctly for both admins and non-admin users. It is irrelevant if UAC is on or off. You should still display the shields, you should still gracefully fail if the user is not an admin (same as you would if the elevation prompt came up and the user cancelled, same as you should if you were running on XP). The academic answer to the original question is that you can read it from the registry (much like the built-in Security Centre does). Since there is no genuine requirement to know this stuff from code, there is no API for it.

So the only question to answer programmatically is how to know if the user has admin rights. I have shown how to do this before but here goes again:

  // using System.Security.Principle;
  private bool IsAdmin()
  {
    WindowsIdentity id = WindowsIdentity.GetCurrent();
    WindowsPrincipal p = new WindowsPrincipal(id);

    return p.IsInRole("Administrators");
  }

I have read blogs where others get further information regarding elevation about the user's account by pinvoking native APIs, but again, I remain totally unconvinced about that need. Your app shouldn't care about anything else: all that matters is if the user has admin rights at the moment your admin code is about to execute, nothing else.

If you disagree and think you have a genuine reason for knowing more than what I describe above, then please post your scenario to the relevant forum linked to from here.

Comments

  • Anonymous
    September 17, 2007
    In VB.NET: If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator)Then  Return True Else  Return False End If

  • Anonymous
    July 05, 2012
    The comment has been removed

  • Anonymous
    January 29, 2013
    "How can I determine if User Account Control is on or off via code?" This is a valid question and some people might want to know the answer to it, not just your opinion whether it should be asked, if you can't answer the question then just say so!!!! I personally would like to know the answer to the above question. I don't want to know how to turn it off, I want to know how to find out if it is on or off.   If this is beyond you then just say so. Cheers