如何获取与特定文件夹关联的图标? [英] How to get the icon associated with a specific folder?
问题描述
在我的一个项目中,我需要从路径中获取特定文件夹的图标。
I was required in one of my projects to get the icon for specific folders from their paths.
例如:
如果我使用 C:\Users\Username\Desktop
我想获取与桌面文件夹关联的图标
如果我使用文件夹的路径有一个自定义图标,我想得到那个图标
For example:
If I use C:\Users\Username\Desktop
I want to get the icon associated with the Desktop folder
If I use the path of a folder that has a custom icon, I want to get that icon
不,我不想要一般默认文件夹图标
我一直在寻找近3天没有运气。任何帮助都表示赞赏。
I've been searching for nearly 3 days with no luck. Any help is appreciated.
推荐答案
您可以使用本机SHGetFileInfo函数。您可以使用.net InteropServices导入它。
You could use the native SHGetFileInfo function. You can import it using the .net InteropServices.
有一篇知识库文章描述了如何操作。
There's a knowledge base article describing how to do it.
http://support.microsoft.com/kb/319350
编辑:
此外
如何使用Shell32.SHGetFileInfo在Windows 7上获取文件夹图标
示例:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace IconTest2
{
public partial class MainWindow : Window
{
//Struct used by SHGetFileInfo function
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
//Constants flags for SHGetFileInfo
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
//Import SHGetFileInfo function
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
public MainWindow()
{
InitializeComponent();
SHFILEINFO shinfo = new SHFILEINFO();
//Call function with the path to the folder you want the icon for
SHGetFileInfo(
"C:\\Users\\Public\\Music",
0, ref shinfo,(uint)Marshal.SizeOf(shinfo),
SHGFI_ICON | SHGFI_LARGEICON);
using (Icon i = System.Drawing.Icon.FromHandle(shinfo.hIcon))
{
//Convert icon to a Bitmap source
ImageSource img = Imaging.CreateBitmapSourceFromHIcon(
i.Handle,
new Int32Rect(0, 0, i.Width, i.Height),
BitmapSizeOptions.FromEmptyOptions());
//WPF Image control
m_image.Source = img;
}
}
}
}
参考for SHGetFileInfo - http:// msdn.microsoft.com/en-us/library/windows/desktop/bb762179(v=vs.85).aspx
Reference for SHGetFileInfo - http://msdn.microsoft.com/en-us/library/windows/desktop/bb762179(v=vs.85).aspx
这篇关于如何获取与特定文件夹关联的图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!