2024年12月30日 星期一

VBA:FORM 具備縮小、關閉按鈕

故事是這樣開始的,小編一開始是透過.show跟.hide方式來控制表單,發現太消耗記憶體了,
所以在想如果表單可以像office一樣可以放大縮小收斂就好了。


圖1.vba表單

與chatgpt討論多次跟測試後,得到以下:

#If VBA7 Then

    Private Declare PtrSafe Function GetWindowLongPtr Lib "user32" Alias "GetWindowLongPtrA" (ByVal hWnd As LongPtr, ByVal nIndex As Long) As LongPtr

    Private Declare PtrSafe Function SetWindowLongPtr Lib "user32" Alias "SetWindowLongPtrA" (ByVal hWnd As LongPtr, ByVal nIndex As Long, ByVal dwNewLong As LongPtr) As LongPtr

    Private Declare PtrSafe Function DrawMenuBar Lib "user32" (ByVal hWnd As LongPtr) As LongPtr

    Private Declare PtrSafe Function FindWindowA Lib "user32" (ByVal lpClassName As String, ByVal lpWindowName As String) As LongPtr

     Private Declare PtrSafe Function ShowWindow Lib "user32" (ByVal hWnd As LongPtr, ByVal nCmdShow As Long) As Long

#Else

    ' 32 位元系統使用這些聲明

    Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long) As Long

    Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

    Private Declare Function DrawMenuBar Lib "user32" (ByVal hWnd As Long) As Long

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

    Private Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long

#End If

Private Const GWL_STYLE As Long = -16

Private Const WS_MINIMIZEBOX As Long = &H20000

Private Const WS_MAXIMIZEBOX As Long = &H10000

Private Const WS_SYSMENU As Long = &H80000

Private Sub UserForm_Initialize()

    Dim hWnd As LongPtr

    Dim lStyle As LongPtr    

    ' 獲取 UserForm 的窗口句柄

    hWnd = FindWindowA("ThunderDFrame", Me.Caption)    

    ' 獲取窗口的當前樣式

    lStyle = GetWindowLongPtr(hWnd, GWL_STYLE)   

    ' 添加最小化和最大化按鈕

    lStyle = lStyle Or WS_MINIMIZEBOX Or WS_MAXIMIZEBOX Or WS_SYSMENU

    SetWindowLongPtr hWnd, GWL_STYLE, lStyle

    ' 刷新菜單欄

    DrawMenuBar hWnd

End Sub


API 函數聲明區塊

GetWindowLongPtr 和 GetWindowLong:用於獲取窗口的屬性。

SetWindowLongPtr 和 SetWindowLong:用於設置窗口的屬性。

DrawMenuBar:用於刷新表單欄以應用新的窗口屬性。

FindWindowA:用於查找特定窗口的句柄。

ShowWindow:用於顯示或隱藏窗口。

常數聲明

GWL_STYLE:用於指定窗口的樣式屬性。

WS_MINIMIZEBOX、WS_MAXIMIZEBOX 和 WS_SYSMENU:分別表示最小化按鈕、最大化按鈕和系統表單。

UserForm 初始化過程

UserForm_Initialize 子程序:當 UserForm 被初始化時調用該子程序來添加最小化和最大化按鈕。

首先,通過 FindWindowA 找到 UserForm 的窗口句柄。

接著,通過 GetWindowLongPtr 獲取當前的窗口樣式。

然後,將最小化和最大化按鈕及系統菜單的樣式添加到窗口樣式中。

最後,使用 SetWindowLongPtr 設置新的窗口樣式,並通過 DrawMenuBar 刷新表單欄以應用更改。

沒有留言:

張貼留言

美元走勢紀錄 2025.01.03