[英]C# Application get runs Twice while running as an administrative
我正在嘗試從啟動時以管理員身份運行我的應用程序。 為此,我編寫了以下代碼:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
Application.Run(new HomePage());
}
else
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
Application.Exit();
}
catch
{
return;
}
Application.Exit();
}
Application.Run(new HomePage());
這是我的 program.cs 文件。 問題是當我運行它時它帶有兩個相同的應用程序。 我嘗試了很多方法,但都沒有解決。
是否可以從啟動時以管理員身份運行我的應用程序而不會引發以管理員身份運行的對話?
您調用 application.run 兩次(如果您是管理員,一次在 if 內部,一次在 if/else 塊之后),因此對於管理員,它將運行兩次。
只需在 if/else 之后刪除 application.run 或反轉您的 if else 來說明 if 不是管理員(您目前在 else 中擁有的內容),不要放置 else 並讓應用程序在最后運行,只會被擊中如果您不是管理員
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
// If you're an administrator
if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
{
// Then run the application (first time)
Application.Run(new HomePage());
}
else
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
Application.Exit();
}
catch
{
return;
}
Application.Exit();
}
// you end up here after it ran as an admin, skipping the else and you tell it to run again, either remove that line or invert your condition
Application.Run(new HomePage());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.