PowerToys/Wox/ImagePathConverter.cs

73 lines
2.3 KiB
C#
Raw Normal View History

using System;
2014-03-10 07:21:26 +08:00
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace Wox
{
public class ImagePathConverter : IMultiValueConverter
{
2014-03-10 07:21:26 +08:00
private static Dictionary<string, object> imageCache = new Dictionary<string, object>();
private static ImageSource GetIcon(string fileName)
{
Icon icon = Icon.ExtractAssociatedIcon(fileName);
2014-03-10 07:21:26 +08:00
if (icon != null)
{
return System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(icon.Handle, new Int32Rect(0, 0, icon.Width, icon.Height), BitmapSizeOptions.FromEmptyOptions());
}
return null;
}
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
2014-03-10 07:21:26 +08:00
object img = null;
2014-02-20 09:34:30 +08:00
if (values[0] == null) return null;
string path = values[0].ToString();
string pluginDirectory = values[1].ToString();
2014-03-10 07:21:26 +08:00
string fullPath = Path.Combine(pluginDirectory, path);
if (imageCache.ContainsKey(fullPath))
{
return imageCache[fullPath];
}
string resolvedPath = string.Empty;
if (!string.IsNullOrEmpty(path) && path.Contains(":\\") && File.Exists(path))
{
resolvedPath = path;
}
2014-03-10 07:21:26 +08:00
else if (!string.IsNullOrEmpty(path) && File.Exists(fullPath))
{
2014-03-10 07:21:26 +08:00
resolvedPath = fullPath;
}
if (resolvedPath.ToLower().EndsWith(".exe") || resolvedPath.ToLower().EndsWith(".lnk"))
{
2014-03-10 07:21:26 +08:00
img = GetIcon(resolvedPath);
}
else if (!string.IsNullOrEmpty(resolvedPath) && File.Exists(resolvedPath))
{
img = new BitmapImage(new Uri(resolvedPath));
}
2014-02-20 18:26:01 +08:00
2014-03-10 07:21:26 +08:00
if (img != null)
2014-02-28 23:21:01 +08:00
{
2014-03-10 07:21:26 +08:00
imageCache.Add(fullPath, img);
2014-02-28 23:21:01 +08:00
}
2014-02-20 18:26:01 +08:00
2014-03-10 07:21:26 +08:00
return img;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
}