问题描述
即使在 Windows 7 中以编程方式固定图标似乎也是不允许的(就像这里所说的那样:http://msdn.microsoft.com/en-us/library/dd378460(v=VS.85).aspx),有一些方法可以做到这一点使用一些 VB 脚本.有人在 C# 中找到了这样的方法:
Even the programmatic pinning of icons in Windows 7 seems it's not permitted (like it says here: http://msdn.microsoft.com/en-us/library/dd378460(v=VS.85).aspx), there are some methods for doing this by using some VB scripts. Someone found a way of doing this in C# like this:
private static void PinUnpinTaskBar(string filePath, bool pin)
{
if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);
// create the shell application object
dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
string path = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
dynamic directory = shellApplication.NameSpace(path);
dynamic link = directory.ParseName(fileName);
dynamic verbs = link.Verbs();
for (int i = 0; i < verbs.Count(); i++)
{
dynamic verb = verbs.Item(i);
string verbName = verb.Name.Replace(@"&", string.Empty).ToLower();
if ((pin && verbName.Equals("pin to taskbar")) || (!pin && verbName.Equals("unpin from taskbar")))
{
verb.DoIt();
}
}
shellApplication = null;
}
可以看出,代码利用了 .NET Framework 4.0 的特性.我想问的问题是:这个函数可以转换成同样的东西,但只使用 3.5 框架吗?有什么想法吗?
As can be seen, the code makes use of .NET Framework 4.0 features. The question I want to ask is: can this function be transformed so it would make the same thing, but using just 3.5 Framework? Any ideas?
推荐答案
简单...
private static void PinUnpinTaskBar(string filePath, bool pin) {
if (!File.Exists(filePath)) throw new FileNotFoundException(filePath);
// create the shell application object
Shell shellApplication = new ShellClass();
string path = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileName(filePath);
Folder directory = shellApplication.NameSpace(path);
FolderItem link = directory.ParseName(fileName);
FolderItemVerbs verbs = link.Verbs();
for (int i = 0; i < verbs.Count; i++) {
FolderItemVerb verb = verbs.Item(i);
string verbName = verb.Name.Replace(@"&", string.Empty).ToLower();
if ((pin && verbName.Equals("pin to taskbar")) || (!pin && verbName.Equals("unpin from taskbar"))) {
verb.DoIt();
}
}
shellApplication = null;
}
请务必添加对Microsoft Shell 控件和自动化"的 COM 引用.
Be sure to add a COM reference to "Microsoft Shell Controls And Automation".
如果您想保留使用 Activator.CreateInstance 的现有方法,这样您就不必拥有额外的 COM 互操作 DLL,那么您将不得不使用反射.但这会使代码更难看.
If you want to keep the existing method of using Activator.CreateInstance so you don't have to have the extra COM interop DLL then you'll have to use reflection. But that would make the code a lot uglier.
这篇关于使用 C# 将 *.lnk 文件固定到 Windows 7 任务栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!