Destroy image after uploading it to ImageList in C #

I looked at stackoverflow about ImageLists, I am confused by the answers / answers. I have the following code what it does; based on the file extension, it captures the Icon . Therefore, when I add a file, say Hello.pdf, I display the file as a list with a .pdf icon similar to Windows Explorer.

 private void bwUpdateSmallImageList_DoWork(object sender, DoWorkEventArgs e) { lock (smImageLock) { foreach (String ext in _Extension) { if (!_SmallImageLists.Images.ContainsKey(ext)) // .jpg/.pdf/.doc { IntPtr handle; IconSize iSize = IconSize.Small; Icon icon = null; try { icon = FileSystemHelper.IconFromFileExtension(ext, iSize, out handle); if (icon != null) { Image b = icon.ToBitmap() as Image; if (b != null) { _SmallImageLists.Images.Add(ext, b); //b.Dispose(); ****1 call dispose ? //icon.Dispose(); ****2 call dispose ? } } DestroyIcon(handle); // this one is being called //[DllImport("user32.dll")] //private static extern bool DestroyIcon(IntPtr hIcon); } catch { }//(TargetInvocationException ex)// we dont want to throw exception from a background worker // if it can not grab the icon just leave it blank } } } } 

After I added to the list of images, should I destroy / destroy the Image b variable, as well as the Icon Icon variable.

In fact, I did not find the correct answer, after adding the icon / image to ImageList , does it copy its own memory space to the image or does it store the memory address of the image / icon? FileSystemHelper.IconFromFileExtension function is as follows;

 public static Icon IconFromFileExtension(string fileExtension, IconSize iconSize, out IntPtr handle) { //Icon icon = null; handle = IntPtr.Zero; try { if (fileExtension.StartsWith(".") == false) fileExtension = "." + fileExtension; SHFILEINFO shFileInfo = new SHFILEINFO(); SHGetFileInfo(fileExtension, 0, ref shFileInfo, (uint)Marshal.SizeOf(shFileInfo), SHGFI_ICON | SHGFI_USEFILEATTRIBUTES | (uint)iconSize); handle = shFileInfo.hIcon; //icon = Icon.FromHandle(shFileInfo.hIcon); //DestroyIcon(handle);// this is wrong, icon needs the handle, can't destroy return Icon.FromHandle(shFileInfo.hIcon); //return icon; } catch(Exception) { //return LanganComponent.Properties.Resources.unknown; return null; } } 

I ask because I get Creation of the ImageList handle did not succeed. My visual studio crashes when I try to debug after getting a crash report in dev.exe , it comes to the point where I tried to copy SmallImageList/LargeImgaeList to ListView .

I tried to get rid of by calling b.Dispose() and icon.Dispose() . But when I do this, I realized that there are no icons. I could return Bitmap using System.Drawing.Icon.ToBitmap() , but instead, I decided to use Icon .

+5
source share

Source: https://habr.com/ru/post/1240360/


All Articles