Skip to content

Instantly share code, notes, and snippets.

@ruyut
Created September 28, 2021 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruyut/602742f3258ac80e343c916e922ba355 to your computer and use it in GitHub Desktop.
Save ruyut/602742f3258ac80e343c916e922ba355 to your computer and use it in GitHub Desktop.
WindowsForms 以系統管理員身分啟動
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