VS2017 打包安裝檔問題–管理者權限

Posted by Eric... On 2018年11月18日 星期日 0 意見
Win10 的安全性比較嚴謹,自行開發的程式安裝後執行會出現漏斗轉個幾下就停止了,這個況狀還不是出現程式無回應就是 Win10 直接就結束程式。最簡單的解決方式是在圖示上按右鍵選擇:以系統管理員身份執行
image
不過要請使用者每回都要選擇”以系統管理員身份執行”,的確是有些麻煩。經過網路找解法,試過 app.manifest 中設定 requireAdministrator,但程式仍直接被 Win10 關閉。最後找到直接寫 code 提示使用者需要系統管理員權限的題示畫面,但使用者只要按下 “是” 就可以執行。
image

以下 sample code 來源: https://dotblogs.com.tw/alexwang/2016/09/21/234628
 [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());
            }
        }

0 意見:

張貼留言