首页 > 一句话 > c#代码创建快捷方式

c#代码创建快捷方式

在前面的文章中,衣服自己洗分享了如何附加程序到任务栏。不过首先,你得有一个快捷方式,我们这里就来分享如何使用c#创建快捷方式。

C#里没有直接创建快捷方式的方法,衣服自己洗也在网上搜索了下,除了本文的代码外,还有利用WHO和vbs的方式,本文是使用直接代码com调用的方式,所谓萝卜白菜各有所爱,大家看着来吧。
代码比较长,总的来说,就是定义了2个结构体,一个类,一个接口,然后就是供外部调用的方法了。这里给出了关键的代码,剩余部分代码见下面的截图。

public static bool CreateShortcut(string shortcutPath, string targetPath, string workingDirectory, string description, string iconLocation = null)
{
const int SW_SHOWNORMAL = 1;
try
{
CShellLink cShellLink = new CShellLink();

IShellLink iShellLink = (IShellLink)cShellLink;
iShellLink.SetDescription(description);
iShellLink.SetShowCmd(SW_SHOWNORMAL);
iShellLink.SetPath(targetPath);
iShellLink.SetWorkingDirectory(workingDirectory);

if (!string.IsNullOrEmpty(iconLocation))
{
iShellLink.SetIconLocation(iconLocation, 0);
}

IPersistFile iPersistFile = (IPersistFile)iShellLink;
iPersistFile.Save(shortcutPath, false);

Marshal.ReleaseComObject(iPersistFile);
iPersistFile = null;
Marshal.ReleaseComObject(iShellLink);
iShellLink = null;
Marshal.ReleaseComObject(cShellLink);
cShellLink = null;

return true;
}
catch //(System.Exception ex)
{
return false;
}
}

shortcut

分类: 一句话 标签: , ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.