我正在尝试设置指向文件夹的快捷方式图标,但找不到有关如何从shell32.dll将快捷方式图标设置为本机图标的任何资源。我在Rykler的msdn上找到了This的答案,但答案已经过时了。任何帮助将不胜感激。
代码
SHFILEINFO shinfo = new SHFILEINFO();
Win32.SHGetFileInfo(filename, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), (int)0x1000);
// icon index # and path
int IconIndex = shinfo.iIcon
string IconPath = shinfo.szDisplayName
shortcut.IconLocation = ???
SHFILEINFO结构(摘自This问题)
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
class Win32
{
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint
dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}
答案 0 :(得分:0)
因此,经过一番研究后,似乎并不太复杂。首先,从this question获取接口声明。在项目中包含声明。
之后,您可以使用以下代码:
public class Q47602417
{
public static void MakeShortcut(string targetPath)
{
var shellLink = new ShellLink();
((IShellLinkW)shellLink).SetDescription("Sample Shortcut");
((IShellLinkW)shellLink).SetPath(targetPath);
((IShellLinkW)shellLink).SetIconLocation(Environment.SystemDirectory + "\\Shell32.dll", 12);
((IPersistFile)shellLink).Save(@"C:\temp\shortcut.lnk", false);
}
}
要添加的一件事:此示例不包含错误检查!您不知道是否创建了快捷方式。因此,更改被调用的接口方法以返回整数并添加异常检查:
//...
int SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
int SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
int SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
//.. omitted other details ...
int Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember);
现在,您可以检查创建快捷方式是否有效。
public class Q47602417
{
public static void MakeShortcut(string targetPath)
{
ShellLink shellLink = new ShellLink();
int hr;
hr = ((IShellLinkW)shellLink).SetDescription("Sample Shortcut");
Marshal.ThrowExceptionForHR(hr);
hr = ((IShellLinkW)shellLink).SetPath(targetPath);
Marshal.ThrowExceptionForHR(hr);
hr = ((IShellLinkW)shellLink).SetIconLocation(Environment.SystemDirectory + "\\Shell32.dll", 12);
Marshal.ThrowExceptionForHR(hr);
hr = ((IPersistFile)shellLink).Save(@"C:\temp\shortcut.lnk", false);
Marshal.ThrowExceptionForHR(hr);
}
}
示例结果: