office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

vba穫取userform窗體的句柄

2020-11-14 08:00:00
OfficeOne
轉貼
5086

 Visual Basic中可以通過HWnd屬性穫取UserForms 的句柄,HWnd屬性提供對窗體的窗口句柄的訪問。

在使用與窗口相關的Windows API時,需要窗口句柄。 但是和 Visual Basic不衕的是VBA UserForms不具有HWnd屬性 


以下例程可讓您穫取VBA UserForms窗口句柄。 

GetUserFormHandle



Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
End Type

Private Declare Function CoCreateGuid Lib "ole32.dll" (G As GUID) As Long
Private Declare Function StringFromGUID2 Lib "ole32.dll" (G As GUID, _
    ByVal str As String, _
    ByVal cchMax As Long) As Long

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" ( _
    ByVal lpClassName As String, _
    ByVal lpWindowName As String) As Long

Private Function GetGUID() As String
    Dim G As GUID
    Dim S As String

    S = String(76, vbNullChar)
    CoCreateGuid G
    StringFromGUID2 G, S, Len(S)
    S = StrConv(S, vbFromUnicode)
    GetGUID = S
End Function

Private Function GetUserFormHandle(ByVal UF As Object)
    Dim S As String
    Dim OrigCaption As String

    S = GetGUID()
    OrigCaption = UF.Caption
    UF.Caption = S
    GetUserFormHandle = FindWindow(vbNullString, S)
    UF.Caption = OrigCaption
End Function

Private Sub UserForm_Initialize()
    MsgBox "UserForm window handle: 0x" + Hex(GetUserFormHandle(Me))
End Sub
分享