网络上绝大多数的C#教程都是使用了 Windows Script Host Object Model 来创建快捷方式,这个方法的弊病是需要引入IWshRuntimeLibrary,在添加引用对话框中搜索Windows Script Host Object Model,选择之后添加到Project的引用中。用户在使用中可能会遇到缺少com组件或者被某些杀毒软件误判的问题。
下面的方法很好的解决了这个问题,不需要引用和using, 而且适应32和64位系统。
[ComImport]
[Guid(“00021401-0000-0000-C000-000000000046”)]
internal class ShellLink
{}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid(“000214F9-0000-0000-C000-000000000046”)]
internal interface IShellLink
{
void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out IntPtr pfd, int fFlags);
void GetIDList(out IntPtr ppidl);
void SetIDList(IntPtr pidl);
void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
void GetHotkey(out short pwHotkey);
void SetHotkey(short wHotkey);
void GetShowCmd(out int piShowCmd);
void SetShowCmd(int iShowCmd);
void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
void Resolve(IntPtr hwnd, int fFlags);
void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
}
private void creatShortcut()
{
IShellLink link = (IShellLink)new ShellLink();
link.SetDescription(“将文件拖放到本快捷方式即可实现文件分拣.”);
link.SetPath(Application.ExecutablePath); //指定文件路径
IPersistFile file = (IPersistFile)link;
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
file.Save(Path.Combine(desktopPath, “文件自动分拣.lnk”), false); //快捷方式保存到桌面
}
One thought to “C# 不用Windows Script Host Object Model创建桌面快捷方式”