日期:2014-05-19  浏览次数:20986 次

用listview实现模拟资源管理器,怎么样实现文件图标和系统的文件关联同步。
比如说不同的文件在资源管理器当中,不同的文件类型会对应着不同的图标,双击的时候会有一个相应的应用程序来打开它。我怎么样才能获得文件类型(扩展名)和文件图标的对应关系?

------解决方案--------------------
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.IO;
namespace App
{
/// <summary>
/// Shell32 的摘要说明。
/// </summary>
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;
};

public enum IconSize : uint
{
Large = 0x0, //32x32
Small = 0x1 //16x16
}

//the function that will extract the icons from a file
public class Shell32
{
const uint SHGFI_ICON = 0x100;
const uint SHGFI_USEFILEATTRIBUTES = 0x10;

[DllImport( "Shell32 ", CharSet=CharSet.Auto)]
internal extern static int ExtractIconEx (
[MarshalAs(UnmanagedType.LPTStr)]
string lpszFile, //size of the icon
int nIconIndex, //index of the icon
//(in case we have more
//then 1 icon in the file
IntPtr[] phIconLarge, //32x32 icon
IntPtr[] phIconSmall, //16x16 icon
int nIcons); //how many to get

[DllImport( "shell32.dll ")]
static extern IntPtr SHGetFileInfo(
string pszPath, //path
uint dwFileAttributes, //attributes
ref SHFILEINFO psfi, //struct pointer
uint cbSizeFileInfo, //size
uint uFlags); //flags

//we need this function to release the unmanaged resource,
//the unmanaged resource will be
//copies to a managed one and it will be returned.
[DllImport( "user32.dll ", CharSet = CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

//will return an array of icons
public static Icon[] IconsFromFile(string Filename,IconSize Size)
{
int IconCount = ExtractIconEx(Filename,-1,
null,null,0); //checks how many icons.
IntPtr[] IconPtr = new IntPtr[IconCount];
Icon TempIcon;

//extracts the icons by the size that was selected.
if (Size == IconSize.Small)
ExtractIconEx(Filename,0,null,IconPtr,IconCount);
else
ExtractIconEx(Filename,0,IconPtr,null,IconCount);

Icon[] IconList = new Icon[IconCount];

//gets the icons in a list.
for (int i = 0; i < IconCount; i++)
{
TempIcon = (Icon) Icon.FromHandle(IconPtr[i]);
IconList[i] = GetManagedIcon(ref TempIcon);
}

return IconList;
}

//extract one selected by index icon from a file.
public static Icon IconFromFile(string Filename,
IconSize Size,int Index)
{
int IconCount = ExtractIconEx(Filename,
-1,null,null,0); //checks how many icons.
if (IconCount <= 0 || Index > = IconCount)
return null; // no icons were found.

Icon TempIcon;
IntPtr[] IconPtr = new IntPtr[1];

//extracts the icon that we want in the selected size.
if (Size == IconSize.Small)
ExtractIconEx(Filename,Index,null,IconPtr,1);
else
ExtractIconEx(Filename,Index,IconPtr,null,1);

TempIcon = Icon.FromHandle(IconPtr[0]);