void RunAdm()
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;// "FastReading.exe";
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
//退出
Environment.Exit(0);
}
/// <summary>
/// 在启动文件夹创建快捷方式
/// </summary>
/// <param name="exePath"></param>
public void CreateLnk(string exePath="") {
if (string.IsNullOrEmpty(exePath))
{
exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
}
string path = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\"+System.IO.Path.GetFileNameWithoutExtension(exePath)+".lnk";
if (System.IO.File.Exists(path))
{
return;
}
try
{
dynamic obj = Activator.CreateInstance(Type.GetTypeFromProgID("WScript.Shell"));
var link = obj.CreateShortcut(path);
link.TargetPath = exePath;
link.WindowStyle = 1;
link.WorkingDirectory = System.IO.Path.GetDirectoryName(exePath);
link.Save();
}
catch
{
//使用管理员权限重新运行
RunAdm();
}
}
C# 开机自动运行
这段代码定义了两个方法,RunAdm()用于以管理员权限启动程序,CreateLnk()则在启动文件夹创建程序的快捷方式。如果快捷方式已存在,程序会跳过。如果在创建快捷方式时遇到权限问题,RunAdm()将被调用来重新运行程序。
摘要由CSDN通过智能技术生成