2010-02-17 49 views

回答

24
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); 
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); 

if (!hasAdministrativeRight) 
{ 
    RunElevated(Application.ExecutablePath); 
    this.Close(); 
    Application.Exit(); 
} 

private static bool RunElevated(string fileName) 
{ 
    //MessageBox.Show("Run: " + fileName); 
    ProcessStartInfo processInfo = new ProcessStartInfo(); 
    processInfo.Verb = "runas"; 
    processInfo.FileName = fileName; 
    try 
    { 
     Process.Start(processInfo); 
     return true; 
    } 
    catch (Win32Exception) 
    { 
     //Do nothing. Probably the user canceled the UAC window 
    } 
    return false; 
} 
+2

這是一個正確的答案,但'RunElevated'可能應該返回一個'bool'因此,如果用戶取消擡高你可以投訴。 – 2010-02-17 19:49:14

+2

另外,由於您要關閉並重新啓動應用程序,因此如果有狀態要保存,請注意這一點。你可能更喜歡分割出需要提升的東西,並在不關閉主應用的情況下啓動提升的東西。 – 2011-01-25 19:24:16

相關問題