Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

c# - Giving application elevated UAC

I have an application which needs the UAC elevation.

I have the code which lets me give that but the application opens twice.. which is the issue..

so here is the code in Form1:

 public Form1()
    {
        InitializeComponent();

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

        if (!hasAdministrativeRight)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.WorkingDirectory = Environment.CurrentDirectory;
            startInfo.FileName = Application.ExecutablePath;
            startInfo.Verb = "runas";
            try
            {
                Process p = Process.Start(startInfo);
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                return;
            }

        }

    }

and this is the code programs.cs

       static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

on debugging i find out that first it executes

Process p = Process.Start(startInfo);

which opens the application UAC elevation dialog and then opens the application

but then it goes to the

Application.Run(new Form1());

in main() and opens the application again.

i dont want it to open the app again...

i am new to this is there anything i am doing wrong and do i need to close the UAC once its open..

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need to meddle with all that to make sure that your application always runs with elevated privileges. You can simply add an application manifest which instructs Windows to run your app elevated, and the UAC prompt will appear without you needing to write a single line of code.

There's a related question with an answer that also describes how to add a manifest here: How can I embed an application manifest into an application using VS2008?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...