[VBA] 如何用 SendMessage 函數為自訂表單加入圖示
1.VBA不像VB6或是.NET功能那麼強大,VB6及VS.NET都有Icon屬性可以直接使用圖示
2.設定Icon屬性後,表單上就會出現Icon圖示了
3.VBA要達到此功能就得靠API了,SendMessage 是常用的API之一,當然不可少。
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
4.還得靠 DrawMenuBar 來重繪。
5.當然也少不了用 FindWindow 來取得視窗的handle value
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
因為VBA功能沒有hWnd屬性,所以得靠 FindWindow 來取得handle value,但是VB6跟VS.Net都有該屬性,但這個屬性只能看自己的handle,要看別人的 handle 還是得靠 FindWindow 的啦。
6.最後搭配 Image1 控制項存放圖片,再將Image1.Visible屬性設為False
7.完整範例如下,執行後就會出現跟第2項一樣的畫面
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function DrawMenuBar Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Long
'發送給某個視窗來返回與某個窗口有關連的大圖標或小圖標的handle
Private Const WM_SETICON = &H80
'圖示SIZE
Private Const ICON_SMALL = 0&
Private Const ICON_BIG = 1&
Dim hWnd As Long
Private Sub UserForm_Initialize()
'取的handle值
hWnd = FindWindow(vbNullString, Me.Caption)
'呼叫副程式改變圖示
Call ChangeIcon(hWnd, Image1.Picture.Handle)
End Sub
'改變圖示
Private Sub ChangeIcon(ByVal hWnd As Long, Optional ByVal hicon As Long = 0&)
'變更大圖示與小圖示
SendMessage hWnd, WM_SETICON, ICON_SMALL, ByVal hicon
SendMessage hWnd, WM_SETICON, ICON_BIG, ByVal hicon
'重繪
DrawMenuBar hWnd
End Sub
8.還有其他方法可以達成上述功能,請參考http://chijanzen.net/wp/?p=281
9.範例下載:定義自訂表單圖示.rar
10.上述的API也可以用VB.Net或C#.NET語言上使用
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET