Shortcut.cs
2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using IWshRuntimeLibrary;
using Microsoft.Win32;
namespace BLL
{
/// <summary>
/// 快捷方式
/// </summary>
public static class Shortcut
{
/// <summary>
/// 创建文件的快捷方式
/// </summary>
/// <returns>成功或失败</returns>
public static bool Create()
{
try
{
string appPath = Process.GetCurrentProcess().MainModule.FileName;
string lnkPath = GetStartupPath();
WshShell shell = new WshShell();
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(lnkPath); //创建快捷方式对象
shortcut.TargetPath = appPath; //指定目标路径
shortcut.WorkingDirectory = Path.GetDirectoryName(appPath); //设置起始位置
shortcut.WindowStyle = 1; //设置运行方式,默认为常规窗口
shortcut.Description = ""; //设置备注
shortcut.IconLocation = appPath; //设置图标路径
shortcut.Save(); //保存快捷方式
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 删除程序的快捷方式
/// </summary>
public static void Delete()
{
string lnkPath = GetStartupPath();
if (System.IO.File.Exists(lnkPath))
System.IO.File.Delete(lnkPath);
}
/// <summary>
/// 快捷方式是否存在
/// </summary>
/// <returns></returns>
public static bool Exists()
{
string directory = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string lnkPath = GetStartupPath();
string[] files = Directory.GetFiles(directory, "*.lnk");
int index = Array.FindIndex(files, arr => arr == lnkPath);
if (index == -1) return false;
else return true;
}
/// <summary>
/// 获取启动文件夹内的快捷方式的lnk文件路径
/// </summary>
/// <returns></returns>
private static string GetStartupPath()
{
string appPath = Process.GetCurrentProcess().MainModule.FileName;
string appName = Path.GetFileNameWithoutExtension(appPath);
string directory = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
string lnkPath = Path.Combine(directory, string.Format("{0}.lnk", appName));
return lnkPath;
}
}
}