Sometimes we need to display different icons according to different file extensions, such as using C # as a resource manager. In C #, you can use icon = system. Drawing. Icon. extractassociatedicon (filefullname) to get the specified file icon. However, icon. extractassociatedicon can only retrieve large icons. To retrieve small icons, you must use APIs.
Using System;
Using System. runtime. interopservices;
Using System. drawing;
Namespace Mynamespace
{
Public Class Fileicon
{
/// <Summary>
/// Get the default icon of a file
/// </Summary>
/// <Param name = "FILENAME"> File Name.
/// It can be a file name, or even a file extension (.*);
/// If you want to get the icon represented by the. ICO file, it must be the complete path of the file.
/// </Param>
/// <Param name = "largeicon"> Large icon? </Param>
/// <Returns> Default file icon </Returns>
Public Static Icon getfileicon ( String Filename, Bool Largeicon)
{
Shfileinfo info = New Shfileinfo ( True );
Int Cbfileinfo = Marshal. sizeof (Info );
Shgfi flags;
If (Largeicon)
Flags = Shgfi. icon | Shgfi. largeicon | Shgfi. usefileattributes;
Else
Flags = Shgfi. icon | Shgfi. smallicon | Shgfi. usefileattributes;
Shgetfileinfo (filename,256,OutInfo ,(Uint) Cbfileinfo, flags );
ReturnIcon. fromhandle (info. hicon );
}
[Dllimport ( " Shell32.dll " )]
Private Static Extern Int Shgetfileinfo
(
String Pszpath,
Uint Dwfileattributes,
Out Shfileinfo psfi,
Uint Cbfileinfo,
Shgfi uflags
);
[Structlayout (layoutkind. Sequential)]
Private Struct Shfileinfo
{
Public Shfileinfo ( Bool B)
{
Hicon = Intptr. Zero; iicon = 0 ; Dwattributes = 0 ; Szdisplayname = "" ; Sztypename = "" ;
}
Public Intptr hicon;
Public Int Iicon;
Public Uint Dwattributes;
[Financialas (unmanagedtype. lpstr, sizeconst = 260 )]
Public String Szdisplayname;
[Financialas (unmanagedtype. lpstr, sizeconst = 80 )]
Public String Sztypename;
};
Private Enum Shgfi
{
Smallicon = Zero X 00000001 ,
Largeicon = Zero X 00000000 ,
Icon = Zero X 00000100 ,
Displayname = Zero X 00000200 ,
Typename = Zero X 00000400 ,
Sysiconindex = Zero X 00004000 ,
Usefileattributes = Zero X 00000010
}
}
}