В данном примере мы рассмотрим получение иконки приложения из любого файла. Мы получаем иконку программы по умолчанию открывающей данный тип файла.
Вам необходимо будет подключить библиотеки:
Вам необходимо будет подключить библиотеки:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Media.Imaging;
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
private class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0;
public const uint SHGFI_SMALLICON = 0x1;
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}
public static BitmapImage GetImageBitmapImage(string filename)
{
try
{
SHFILEINFO shinfo = new SHFILEINFO();
IntPtr ptr = Win32.SHGetFileInfo(filename, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
Icon icon = Icon.FromHandle(shinfo.hIcon);
MemoryStream ms = new MemoryStream();
icon.Save(ms);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
return bi;
}
catch
{
return null;
}
}
public static Icon GetImageIcon(string filename)
{
try
{
SHFILEINFO shinfo = new SHFILEINFO();
IntPtr ptr = Win32.SHGetFileInfo(filename, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
Icon icon = Icon.FromHandle(shinfo.hIcon);
return icon;
}
catch
{
return null;
}
}
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapImage));
enc.Save(outStream);
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);
return new Bitmap(bitmap);
}
}
private void button1_Click(object sender, EventArgs e)
{
Icon a = GetImageIcon(@"C:Windowsexplorer.exe");
Image im = a.ToBitmap();
pictureBox1.Image = im;
BitmapImage b = GetImageBitmapImage(@"C:Windowsexplorer.exe");
Image i = BitmapImage2Bitmap(b);
pictureBox2.Image = i;
}
0.00 (0%) 0 votes









