说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

VB如何从文件中提取图标

HTML文档下载 WORD文档下载 PDF文档下载
VB如何从文件中提取图标



使用下面的示例,你可以方便地从EXE,DLL及ICO文件中提取图标。该示例程序使用ExtractIconEX API函数从文件中提取图标,并返回图标句柄,然后利用该句柄,使用DrawIcon函数将图标绘制到目标设备中。最后清除句柄以释放系统资源。

创建新工程后,在工程中添加对Standard OLE Types的引用,然后在工程中添加一个标准模块。将下面的代码粘贴到标准模块中:

Option Explicit

Private Type PicBmp
Size As Long
tType As Long
hBmp As Long
hPal As Long
Reserved As Long
End Type
Private Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Private Declare Function OleCreatePictureIndirect Lib "olepro32.dll" (PicDesc As PicBmp, RefIID As GUID, _
ByVal fPictureOwnsHandle As Long, IPic As IPicture) As Long

Private Declare Function ExtractIconEx Lib "shell32.dll" Alias "ExtractIconExA" (ByVal lpszFile As String, ByVal _
nIconIndex As Long, phiconLarge As Long, phiconSmall As Long, ByVal nIcons As Long) As Long

Private Declare Function DestroyIcon Lib "user32" (ByVal hicon As Long) As Long

Public Function GetIconFromFile(FileName As String, IconIndex As Long, UseLargeIcon As Boolean) As Picture

'参数:
'FileName - 包含有图标的文件 (EXE or DLL)
'IconIndex - 欲提取的圉标的索引,从零开始
'UseLargeIcon-如设置为True,则提取大图标,否则提取小图标
'返回值: 包含标标的Picture对象

Dim hlargeicon As Long
Dim hsmallicon As Long
Dim selhandle As Long

' IPicture requires a reference to "Standard OLE Types."
Dim pic As PicBmp
Dim IPic As IPicture
Dim IID_IDispatch As GUID

If ExtractIconEx(FileName, IconIndex, hlargeicon, hsmallicon, 1) > 0 Then

If UseLargeIcon Then
selhandle = hlargeicon
Else
selhandle = hsmallicon
End If

' Fill in with IDispatch Interface ID.
With IID_IDispatch
.Data1 = &H20400
.Data4(0) = &HC0
.Data4(7) = &H46
End With
' Fill Pic with necessary parts.
With pic
.Size = Len(pic) ' Length of structure.
.tType = vbPicTypeIcon ' Type of Picture (bitmap).
.hBmp = selhandle ' Handle to bitmap.
End With

' Create Picture object.
Call OleCreatePictureIndirect(pic, IID_IDispatch, 1, IPic)

' Return the new Picture object.
Set GetIconFromFile = IPic

DestroyIcon hsmallicon
DestroyIcon hlargeicon

End If
End Function
在窗体中添加一个PictureBox控件和一个命令按钮,把下面的代码加入到命令按钮的Click事件中:

Set Picture1.Picture = GetIconFromFile("c:\windows\moricons.dll", _ 0, True)

按F5运行程序,点击命令按钮后,PictureBox会将文件moricons.dll中的图标索引为零的图标画到PictureBox中。

备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘