C# 程序设计开机启动和桌面快捷方式
标签:folder exists getattr att 目标 stat quic vat erp
文章转自:https://www.cnblogs.com/hh8888-log/p/10687986.html
由于这位大佬贴的是图,我就把对应的代码整了整放上来了
using IWshRuntimeLibrary;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
namespace HCDCapp.Main
{
public class AutoStart
{
//快捷方式名称
private const string QuickName = "软件名称";
//系统自启动目录
private static string SystemStartPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.Startup); } }
//当前程序的完整路径
private static string AppAllPath { get { return Process.GetCurrentProcess().MainModule.FileName; } }
//自动获取桌面 的目录
private static string DesktopPath { get { return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); } }
///
/// 设置开机自动启动
///
///
public static void setAutoStart(bool on = true)
{
//获取启动路径应用程序快捷方式的路径集合
List shortCutPaths = getQuickFromFolder(SystemStartPath, AppAllPath);
if (on)
{
//开机启动
if (shortCutPaths.Count >= 2)
{
for (int i = 1; i 0)
{
for (int i = 0; i
/// 获取指定文件夹下的快捷方式路径集合
///
///
///
///
private static List getQuickFromFolder(string dir, string targetPath)
{
List tmpStrs = new List();
string[] files = Directory.GetFiles(dir, "*.lnk");
if (files == null || files.Length
/// 获取快捷方式的目标文件路径,用于判断是否已经开启了自动启动
///
///
///
private static string getAppPathFromQuick(string shortcutPath)
{
if (System.IO.File.Exists(shortcutPath))
{
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
return shortcut.TargetPath;
}
else
{
return string.Empty;
}
}
///
/// 创建快捷方式
///
///
///
///
///
///
///
private static bool createShortcut(string dir, string shortcutName, string targetPath, string description = null, string iconLocation = null)
{
try
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
//合成快捷方式路径
string shortcutPath = Path.Combine(dir, string.Format("{0}.lnk", shortcutName));
//创建快捷方式对象
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutPath);
shortcut.TargetPath = targetPath;//指定目标路径
shortcut.WorkingDirectory = Path.GetDirectoryName(targetPath);//设置起始位置
shortcut.WindowStyle = 1;//设定运行方式为常规
shortcut.Description = description;//设定备注
shortcut.IconLocation = string.IsNullOrWhiteSpace(iconLocation) ? targetPath : iconLocation;//设置图标路径
shortcut.Save();
return true;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
throw;
}
}
///
/// 删除文件
///
///
private static void deleteFile(string path)
{
FileAttributes attrs = System.IO.File.GetAttributes(path);
if (attrs == FileAttributes.Directory)
{
Directory.Delete(path, true);
}
else
{
System.IO.File.Delete(path);
}
}
}
}
C# 程序设计开机启动和桌面快捷方式
标签:folder exists getattr att 目标 stat quic vat erp
原文地址:https://www.cnblogs.com/echizen/p/13027120.html
评论