【发布时间】:2015-11-24 01:51:58
【问题描述】:
我在 Program.cs 中有一个带有以下代码的 winform 应用程序,以确保我的应用程序始终以管理权限运行:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Init visual styles
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Check if app is launched with administrative privilage
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool administrativeMode = principal.IsInRole(WindowsBuiltInRole.Administrator);
// Check if application is already running
bool mutexCheck;
var mutex = new Mutex(true, Assembly.GetExecutingAssembly().GetType().GUID.ToString(), out mutexCheck);
if (!mutexCheck)
{
// Error
Utils.ShowError("Program is already running.");
return;
}
// If app is running without administrative privilage
if (!administrativeMode)
{
// Request administrative privilage
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.Verb = "runas";
startInfo.FileName = Application.ExecutablePath;
try
{
// Run app as administrator
Process.Start(startInfo);
}
catch (Exception ex)
{
// Error
Utils.ShowError("Program failed to start - " + ex.Message);
return;
}
}
return;
// Launch application
Application.Run(new MyApp());
GC.KeepAlive(mutex);
}
}
每次我在 Visual Studio 2015 中按F5 以调试模式运行应用程序时,应用程序似乎只是在运行 - 调试环境未启动。
所以,我要做的是转到Debug -> Attach to Process... 并选择MyApp.exe,然后我会收到这个窗口的提示:
然后当我点击Restart under different credentials - VS2015 重新启动。然后我将不得不关闭已经运行的 MyApp 实例,然后按F5 以提升权限重新启动;当我这样做时 - 调试工作。
有没有办法将我的 VS2015 设置为始终以提升的权限运行这个项目?
【问题讨论】:
标签: c# winforms permissions visual-studio-2015