获取快捷方式的目标和参数

259 篇文章 4 订阅

来源: 作者: 2006-10-20 出处:pcdog.com

 

    我看了Michael Taupitz关于建立快捷方式的方法,我认为有很多时候当我
们在命令行模式中偶然发现一个快捷方式的时候,我们不知道这个.lnk文件指
向什么地方。

我写了一个函数,它以CString的形式返回了.lnk文件的目标和参数。

CString GetShortcutTarget(const CString LinkFileName)
{
HRESULT hres;

CString Link, Temp = LinkFileName;
Temp.MakeLower();
if (Temp.Find(".lnk")==-1)           //Check if the name ends with .lnk
Link = LinkFileName + ".lnk";   //if not, append it
else
Link = LinkFileName;

CString Info;
Info.Empty();

IShellLink* psl;

//Create the ShellLink object
hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
IID_IShellLink, (LPVOID*) &psl);

if (SUCCEEDED(hres))
{
IPersistFile* ppf;
//Bind the ShellLink object to the Persistent File
hres = psl->QueryInterface( IID_IPersistFile, (LPVOID *) &ppf);
if (SUCCEEDED(hres))
{
WORD wsz[MAX_PATH];
//Get a UNICODE wide string wsz from the Link path
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, Link, -1, wsz,      MAX_PATH);

//Read the link into the persistent file
hres = ppf->Load(wsz, 0);

if (SUCCEEDED(hres))
{
//Read the target information from the link object
//UNC paths are supported (SLGP_UNCPRIORITY)
psl->GetPath(Temp.GetBuffer(1024), 1024, NULL,               SLGP_UNCPRIORITY);
Temp.ReleaseBuffer();
Info = Temp;

//Read the arguments from the link object
psl->GetArguments(Temp.GetBuffer(1024), 1024);
Temp.ReleaseBuffer();
Info += " " + Temp;
}
}
}
psl->Release();
//Return the Target and the Argument as a CString
return Info;
}

在C#中,你可以使用`System.Diagnostics.ProcessStartInfo`和`System.Environment.GetFolderPath`等类来获取快捷方式的相关信息。以下是获取快捷方式信息的一种常见方法: ```csharp using System; using System.Diagnostics; public class ShortcutInfo { public static void GetShortcutDetails(string shortcutPath) { try { using (ProcessStartInfo startInfo = new ProcessStartInfo(shortcutPath)) { // 解析快捷方式 string targetPath = startInfo.FileName; // 获取快捷方式指向的目标程序的完整路径 if (!string.IsNullOrEmpty(targetPath)) { Console.WriteLine($"目标路径: {targetPath}"); } else { Console.WriteLine("无法解析快捷方式目标"); } // 获取图标路径 string iconLocation = GetIconLocation(shortcutPath); if (!string.IsNullOrEmpty(iconLocation)) { Console.WriteLine($"图标路径: {iconLocation}"); } else { Console.WriteLine("无法获取图标位置"); } } } catch (Exception ex) { Console.WriteLine($"异常: {ex.Message}"); } } private static string GetIconLocation(string shortcutPath) { return System.IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.Programs), Path.GetFileNameWithoutExtension(shortcutPath) + ".lnk", "Icon"); } } // 调用示例 string shortcutPath = @"C:\Users\YourUsername\Desktop\MyShortcut.lnk"; ShortcutInfo.GetShortcutDetails(shortcutPath); ``` 这个例子展示了如何通过`ProcessStartInfo`解析快捷方式的文件名(即指向的实际程序),以及尝试获取其图标路径。如果需要更详细的属性(如工作目录、命令行参数等),可能需要进一步分析快捷方式本身的内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值