使用C#将Lnk文件固定到Win 7任务栏

3
即使在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 Framework的方式实现相同的功能?有什么想法吗? 谢谢!


用户已经有了将程序固定到任务栏的方法。为什么需要发明另一种方法呢? - David Heffernan
1个回答

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;
}

这会抛出带有错误代码DISP_E_MEMBERNOTFOUND的ComException。 - msbg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接