hey,
yesterday i asked about filling a datagrid. It chrashed after filling it too often with a class. But after testing i was able to identify the source of the Memory leak. To get the Icon for the proper file i use following methods:
[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;
};
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);
}
IntPtr hImgSmall; //the handle to the system image list
IntPtr hImgLarge; //the handle to the system image list
SHFILEINFO shinfo = new SHFILEINFO();
System.Drawing.Icon ico;
public System.Windows.Media.ImageSource GetIcon(string path, bool IsFolder, bool GetSmall)
{
try
{
if (GetSmall)
hImgSmall = Win32.SHGetFileInfo(path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
else
hImgLarge = Win32.SHGetFileInfo(path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
ico = System.Drawing.Icon.FromHandle(shinfo.hIcon);
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(ico.Handle, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
catch
{
if (IsFolder)
return new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/Resources\\foldericon.jpg", UriKind.RelativeOrAbsolute));
else
return new System.Windows.Media.Imaging.BitmapImage(new Uri("pack://application:,,,/Resources\\filedefaulticon.png", UriKind.RelativeOrAbsolute));
}
}The Last and main Method (GetIcon()), is the problem,
the line: ico = System.Drawing.Icon.FromHandle(shinfo.hIcon); pumps the Memory!!!!!
So i tried something and tried following to tet the application:
if (GetSmall)
hImgSmall = Win32.SHGetFileInfo(path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
else
hImgLarge = Win32.SHGetFileInfo(path, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
ico = System.Drawing.Icon.FromHandle(shinfo.hIcon);
ico.Dispose();
// return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(ico.Handle, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
return null;only if supress the creation of the ico, the application runs fine.
Has anyone experiences with thisproblem??