简体   繁体   中英

C# Icon in XAML

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?

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM