[C#] [WinForm] 強迫使用系統管理員(administrator)開啟程式 (轉)

  • 196
  • 0

[C#] [WinForm] 強迫使用系統管理員(administrator)開啟程式 (轉)

 

[STAThread]
        static void Main()
        {
            var wi = WindowsIdentity.GetCurrent();
            var wp = new WindowsPrincipal(wi);

            if (!wp.IsInRole(WindowsBuiltInRole.Administrator))
            {
                var processInfo = new ProcessStartInfo();
                // The following properties run the new process as administrator
                processInfo.UseShellExecute = true;
                processInfo.FileName = Application.ExecutablePath;
                processInfo.Verb = "runas";

                // Start the new process
                try
                {
                    Process.Start(processInfo);
                }
                catch (Exception ex)
                {
                    // The user did not allow the application to run as administrator
                    MessageBox.Show("Sorry, this application must be run as Administrator.\n" + ex.Message);
                }

            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form2());
            }
        }

https://dotblogs.com.tw/alexwang/2016/09/21/234628