I have a file on a binary in the database, which I'm not loading until the user double clicks on the item (with it's Icon)
ExtractAssociatedIcon should be solving this (I've seen it here: ExtractAssociatedIcon returns null)
But this asks for the existance of the document on a path, (which I don't have), How can I associate to the extension of the tentative file (example: "something.docx"
) which extension the user has associated on his pc to the Icon I should show?
@Edit: I may be able to pull out the content (byte[]) from the database, if that is useful to get the icon asociated to the image. (however, it may also take forever to transfer each file byte[] just to set the icon image).
Also this example of @MatthewWatson is what we are actually using to get it but it takes like 8 seconds on each object value = rkFileIcon.GetValue("");
line, which has 8.4k items to iterate.
@@Edit: Also tried
public static Icon GetIconOldSchool(string fileName)
{
ushort uicon;
StringBuilder strB = new StringBuilder(fileName);
IntPtr handle = ExtractAssociatedIcon(IntPtr.Zero, strB, out uicon);
Icon ico = Icon.FromHandle(handle);
return ico;
}
With no success.
@@@Edit: This one above gives me the icon of a file.(and not the docx icon when it gets a .docx)
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
static SHFILEINFO shinfo = new SHFILEINFO();
class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}
public static Icon YetAnotherAttempt(string fName)
{
//Use this to get the small Icon
var hImgSmall = Win32.SHGetFileInfo(fName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
//Use this to get the large Icon
//hImgLarge = SHGetFileInfo(fName, 0,
// ref shinfo, (uint)Marshal.SizeOf(shinfo),
// Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
//The icon is returned in the hIcon member of the shinfo struct
return System.Drawing.Icon.FromHandle(shinfo.hIcon);
}
@@@@Edit: The results of @AlexK. solution.
The FileToImage Converter is where I'm doing the magic.
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Converter={StaticResource FileToImage}}" />
<TextBlock Text="{Binding FileName}"
Margin="5,0,0,0"
VerticalAlignment="Center"/>
</StackPanel>