Repository navigation
Expand file tree
/
Copy pathStackAppIcon.cs
More file actions
51 lines (48 loc) · 2.43 KB
/
Copy pathStackAppIcon.cs
File metadata and controls
51 lines (48 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Runtime.InteropServices;
internal static class StackAppIcon
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct ShellFileInfo
{
public IntPtr Icon;
public int IconIndex;
public uint Attributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string DisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string TypeName;
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
static extern int SHParseDisplayName(string name, IntPtr bindingContext, out IntPtr pidl,
uint attributes, out uint returnedAttributes);
[DllImport("shell32.dll", EntryPoint = "SHGetFileInfoW", CharSet = CharSet.Unicode)]
static extern IntPtr SHGetFileInfo(IntPtr pidl, uint attributes, ref ShellFileInfo info, uint size, uint flags);
[DllImport("shell32.dll")] static extern void ILFree(IntPtr pidl);
[DllImport("user32.dll")] static extern bool DestroyIcon(IntPtr icon);
public static Icon? Load(StackAppMember member)
{
// AppsFolder also provides the actual logo for packaged apps, whose
// process executable is only a Windows host and cannot launch them.
if (!string.IsNullOrWhiteSpace(member.AppId) && member.AppId.Length <= 256)
{
IntPtr pidl = IntPtr.Zero;
try
{
if (SHParseDisplayName($"shell:AppsFolder\\{member.AppId}", IntPtr.Zero, out pidl, 0, out _) == 0 &&
pidl != IntPtr.Zero)
{
var info = new ShellFileInfo();
if (SHGetFileInfo(pidl, 0, ref info, (uint)Marshal.SizeOf<ShellFileInfo>(),
0x000000008 | 0x000000100 | 0x000000000) != IntPtr.Zero && info.Icon != IntPtr.Zero)
{
try { return (Icon)Icon.FromHandle(info.Icon).Clone(); }
finally { DestroyIcon(info.Icon); }
}
}
}
catch (Exception ex) when (ex is COMException or ArgumentException or ExternalException) { }
finally { if (pidl != IntPtr.Zero) ILFree(pidl); }
}
if (member.LaunchPath is not { Length: > 0 } path || !File.Exists(path)) return null;
try { return Icon.ExtractAssociatedIcon(path); }
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException) { return null; }
}
}