use*_*084 11 c# asp.net uac winforms
我有一个需要UAC提升的应用程序.
我有代码,让我给出,但应用程序打开两次..这是问题..
所以这是Form1中的代码:
public Form1()
{
InitializeComponent();
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
if (!hasAdministrativeRight)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
Process p = Process.Start(startInfo);
}
catch (System.ComponentModel.Win32Exception ex)
{
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是代码programs.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Run Code Online (Sandbox Code Playgroud)
在调试时我发现它首先执行
进程p = Process.Start(startInfo);
这将打开应用程序UAC提升对话框,然后打开应用程序
但后来它去了
Application.Run(new Form1());
在main()中再次打开应用程序.
我不希望它再次打开应用程序...
我是新手,这是我做错了什么,我需要关闭UAC一旦打开..
谢谢
Jon*_*Jon 29
您无需干涉所有这些以确保应用程序始终以提升的权限运行.您只需添加一个应用程序清单,指示Windows运行您提升的应用程序,并且无需编写单行代码即可显示UAC提示.
有一个相关的问题,答案也描述了如何在此处添加清单:如何使用VS2008将应用程序清单嵌入到应用程序中?
小智 6
将 WindowsPrincipal 代码从 Form 移至 Program.cs,如下例所示。这将在启动任何表单之前提示用户输入 UAC 权限,并且仅在已授予 UAC 权限的情况下才启动表单。
static void Main()
{
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator);
if (!hasAdministrativeRight)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
startInfo.Verb = "runas";
try
{
Process p = Process.Start(startInfo);
Application.Exit();
}
catch (System.ComponentModel.Win32Exception ex)
{
MessageBox.Show("This utility requires elevated priviledges to complete correctly.", "Error: UAC Authorisation Required", MessageBoxButtons.OK);
// Debug.Print(ex.Message);
return;
}
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
40112 次 |
最近记录: |