gpt4 book ai didi

c# - 使用 C# 将 lnk 文件固定到 Windows 7 任务栏

转载 作者:行者123 更新时间:2023-11-30 18:41:22 25 4
gpt4 key购买 nike

即使在 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?有任何想法吗?谢谢!

最佳答案

我删除了 dynamic 的使用,并将其替换为反射调用。它很丑陋,除了确保它在 .NET 3.5 下编译之外我没有测试它,但试一试。您需要将 using System.Reflection; 添加到您的类(class)中,如果您还没有的话。

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

关于c# - 使用 C# 将 lnk 文件固定到 Windows 7 任务栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6885964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com