c# - 是否可以将应用程序配置为在 Windows 启动时启动而不需要管理员权限?
问题描述
我有一个WPF
应用程序,我想提供一个复选框,用于配置该应用程序是否会在 Windows 启动时启动(或不启动)。
现在,我可以使用它:
void ManageRunOnStartup(bool runOnStartup)
{
var shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "myApp.lnk");
var shortcutExists = System.IO.File.Exists(shortcutPath);
if (runOnStartup)
{
if (shortcutExists == false)
CreateShortcut(shortcutPath);
}
else if (shortcutExists)
{
System.IO.File.Delete(shortcutPath);
}
}
void CreateShortcut(string shortcutPath)
{
var appLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
var shell = new WshShell();
var shortcut = shell.CreateShortcut(shortcutPath) as IWshShortcut;
shortcut.TargetPath = appLocation;
shortcut.WorkingDirectory = Path.GetDirectoryName(appLocation);
shortcut.Save();
}
问题是,要在文件夹中写入/删除Environment.SpecialFolder.Startup
文件,该应用程序需要管理员权限:(
有没有办法达到相同的结果但不需要管理员权限?
解决方案
如果一个程序是否需要管理员权限,首先是 Manifest。Wich 被放入可执行文件中,因此不受影响。
如果您有一些其他代码启动应用程序(如任务调度程序或服务管理器),您当然可以指定较低权限设置/特定用户。如果你得到了它的权利。
也可以在程序启动期间存储一个值并检查它 - 以及程序是否运行提升。然后尝试使用 Elevation 重新启动。Application.Run 有海拔请求。
反过来摆脱提升的权利根本不是一件容易的事。
编辑:这里有一些关于如何以编程方式启动任何提升程序的代码。
using System;
using System.Diagnostics;
using System.IO;
namespace RunAsAdmin
{
class Program
{
static void Main(string[] args)
{
/*Note: Running a batch file (.bat) or similar script file as admin
Requires starting the interpreter as admin and handing it the file as Parameter
See documentation of Interpreting Programm for details */
//Just getting the Absolute Path for Notepad
string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
string FullPath = Path.Combine(windir, @"system32\notepad.exe");
//The real work part
ProcessStartInfo startInfo = new ProcessStartInfo(FullPath);
startInfo.Verb = "runas";
System.Diagnostics.Process.Start(startInfo);
}
}
}
推荐阅读
- xcode - 错误:找不到吸气剂:'nonVirtual'。编译设备仿真时
- mysql - 用c程序连接mysql数据库
- html - 弹出隐藏溢出外的图像
- c# - 如何使用 linerenderer 绘制一个圆圈并将其作为对象的子对象的圆圈应该在周围绘制?
- couchdb - 多字段的 CouchDB 搜索
- groovy - 为什么在使用 Groovy 在 SOAP UI 中自动化 REST API 时出现意外的令牌错误
- css - 如何在离子5中将块按钮放置在页面末尾
- python - Python - 如何优化代码以更快地运行?(DataFrame 中有很多 for 循环)
- php - 致命错误:未捕获的错误:在 C:\xampp\htdocs\shop\index.php 中调用 null 上的成员函数 query()
- xamarin - 如何在没有 ViewModel 的情况下为 Xamarin 窗体 IOS 后退按钮绑定命令