Created
September 28, 2021 09:10
-
-
Save ruyut/602742f3258ac80e343c916e922ba355 to your computer and use it in GitHub Desktop.
WindowsForms 以系統管理員身分啟動
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Security.Principal; | |
using System.Windows.Forms; | |
namespace RuyutAdministratorStart | |
{ | |
static class Program | |
{ | |
/// <summary> | |
/// The main entry point for the application. | |
/// </summary> | |
[STAThread] | |
static void Main() | |
{ | |
// 判斷是否以系統管理員身分啟動 | |
if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) | |
{ | |
Application.EnableVisualStyles(); | |
Application.SetCompatibleTextRenderingDefault(false); | |
Application.Run(new Form1()); | |
} | |
else | |
{ | |
// 以系統管理員身分重新啟動 | |
var processInfo = new ProcessStartInfo | |
{ | |
UseShellExecute = true, | |
FileName = Application.ExecutablePath, | |
Verb = "runas", | |
}; | |
try | |
{ | |
Process.Start(processInfo); | |
} | |
catch (Exception ex) | |
{ | |
// 授予系統管理員身分被拒絕 | |
MessageBox.Show("本程式必須以系統管理員身分啟動!\n錯誤訊息:" + ex.Message); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment