Posts Tagged ‘snippet’

Snippet: Icon from shell to ImageSource with alpha channel

Thursday, May 21st, 2009

The following code snippet performs the following task:

  1. Get icon of the given file
  2. Convert in a bitmap preserving the alpha channel
  3. Convert it in a ImageSource

This code is shortcut to retrieve the displayed icon of a file. alternative way to do this is useing shell32.dll and SHGetFileInfo.

I have not used IconBitmapDecoder becuase this class lost the alpha channel.

   1:  public BitmapSource GetIconFromPath(string path)
   2:  {
   3:      System.Drawing.Icon icon = System.Drawing.Icon.ExtractAssociatedIcon(path);
   4:      System.Drawing.Bitmap bitmap = icon.ToBitmap();
   5:      return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(),
   6:              IntPtr.Zero, System.Windows.Int32Rect.Empty,
   7:              System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
   8:  }

Snippet: Enable Low Fragmentation Heap for all heaps

Monday, February 23rd, 2009

The following code is a code snippet that enable the Low Fragmentation Heap for all heaps. Remembers that a process has at last one heap but for example a CRT console application has practically at last two heaps. The first heap is default heap of process and the second is the CRT heap. If you use a lot of external DLLs is very common that one of this DLL allocate a private heap.

   1:  // code snippet that try to enable LFH for all heaps of your runnig program.
   2:      HANDLE* hHeaps = NULL;
   3:      int numHeap = GetProcessHeaps(0, NULL);
   4:      if(numHeap > 0)
   5:      {
   6:          ULONG ulEnableLFH = 2;
   7:          hHeaps = (HANDLE*)malloc(sizeof(HANDLE)*numHeap);
   8:          if(GetProcessHeaps(numHeap, hHeaps) == numHeap)
   9:          {
  10:              for(int i = 0; i < numHeap; i++)
  11:              {
  12:                  if(!HeapSetInformation(hHeaps[i], HeapCompatibilityInformation, &ulEnableLFH, sizeof(ulEnableLFH)))
  13:                  {
  14:                      printf("Failed to enable LFH for heap %d.", i);
  15:                  }
  16:              }
  17:          }
  18:          else
  19:          {
  20:              // quite strange !!!
  21:          }
  22:          free(hHeaps);
  23:      }

Suggested reading Windows Internals 4th edition for more details.