0

My aim is to obtain the icons for installed programs and show these icons in WPF application. My steps are as follow:

  1. Get all the exe location, eg. C:\Windows\notepad.exe
  2. Get the Icon object, using Icon anIcon = Icon.ExtractAssociatedIcon(string)
  3. Convert the icon to bitmap, using anIcon.ToBitmap()
  4. insert bitmap in the application

But how should I do 4., the insertion? In XAML, you have <Image Source={xxx} />. But the source is the location of the file. So how should I insert the bitmap into the XAML?

dkozl
  • 32,814
  • 8
  • 87
  • 89
Cheung Brian
  • 715
  • 4
  • 11
  • 29
  • Do you have the Bitmap in code as a `BitmapSource` or something? You should be able to bind it via `{Binding MyImageProperty}` to your ViewModel (if you use MVVM) or the DataContext that you use. Where is your Bitmap currently located and how do the view know about it? – default Feb 25 '14 at 09:43
  • http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap – James Feb 25 '14 at 09:44
  • I generate the Bitmap object in step 3. So, please let me ask the question even more directly. Now I am in step 3. How should I proceed to insert this bitmap in WPF app? – Cheung Brian Feb 25 '14 at 09:55

2 Answers2

1

You can use FileStream and BitmapImage to achieve this.

using(FileStream Fs = new FileStream("path",FileMode.Open,FileAccess.Read))
{

    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.BeginInit();
    bitmapImage.StreamSource = Fs;
    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    bitmapImage.EndInit();

    image.source = bitmapImage;
}
George Chondrompilas
  • 3,167
  • 27
  • 35
1

You can use System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon to create the ImageSource from the Icon.

System.Windows.Media.ImageSource iconSource;
using (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(FilePath))
{
    iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
    sysicon.Handle,
    System.Windows.Int32Rect.Empty,
    System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
return iconSource;

Sample Program - Get Icon From FileName in WPF

Carbine
  • 7,849
  • 4
  • 30
  • 54