Pin lnk文件使用C#赢得7个任务栏

时间:2011-07-29 12:06:35

标签: c#

即使Win7中的图标的程序化固定似乎是不允许的(就像它在这里说的那样:http://msdn.microsoft.com/en-us/library/dd378460(v=VS.85).aspx),有些方法可以通过一些VB脚本来实现。有人在C#中找到了这样做的方法:

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框架?有任何想法吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

我删除了dynamic的使用并将其替换为反射调用。这很丑陋,我没有测试它,除了确保它在.NET 3.5下编译,但是给它一个镜头。如果您还没有using System.Reflection;,则需要将private static void PinUnpinTaskBar(string filePath, bool pin) { if (!File.Exists(filePath)) throw new FileNotFoundException(filePath); // create the shell application object var shellType = Type.GetTypeFromProgID("Shell.Application"); var shellApplication = Activator.CreateInstance(shellType); string path = Path.GetDirectoryName(filePath); string fileName = Path.GetFileName(filePath); var directory = shellType.InvokeMember("Namespace", BindingFlags.InvokeMethod, null, shellApplication, new object[] { path }); var link = directory.GetType().InvokeMember("ParseName", BindingFlags.InvokeMethod, null, directory, new object[] {fileName}); var verbs = link.GetType().InvokeMember("Verbs", BindingFlags.InvokeMethod, null, link, new object[] { }); int verbsCount = (int)verbs.GetType().InvokeMember("Count", BindingFlags.InvokeMethod, null, verbs, new object[] { }); for (int i = 0; i < verbsCount; i++) { var verb = verbs.GetType().InvokeMember("Item", BindingFlags.InvokeMethod, null, verbs, new object[] { i }); var namePropertyValue = (string)verb.GetType().GetProperty("Name").GetValue(verb, null); var verbName = namePropertyValue.Replace(@"&", string.Empty).ToLower(); if ((pin && verbName.Equals("pin to taskbar")) || (!pin && verbName.Equals("unpin from taskbar"))) { verbs.GetType().InvokeMember("DoIt", BindingFlags.InvokeMethod, null, verbs, new object[] { }); } } shellApplication = null; } 添加到您的班级。

{{1}}