Alright, you’ve built an amazing Userform for your user, which works perfectly on every single function. A master piece of software! But, something remains out of your control, a simple click and everything is lost due to… the infamous close button! Ok, you know there is an easy and clever way to avoid this situation, handling the Query_Close event and the Cancel parameter.
So far so good, but… why do you and your user need this button there? Until this question remains unsolved, let’s look to another way to set our lives free about this problem.
Uma necessidade comum em alguns sistemas VBA é evitar que o usuário feche o form involuntariamente. A forma mais comum é captura o evento Query_Close e alterar o valor do parâmetro Cancel.
Porém algumas vezes é necessário que o botão de fechamento nem apareça para alterar. Para isso, basta colocar o código abaixo em um UserForm VBA. Os eventos Initialize e Query_Close já criados tratam de remover o botão do UserForm.
Private Declare Function FindWindowA Lib "USER32" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowLongA Lib "USER32" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLongA Lib "USER32" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Sub UserForm_Initialize()
Dim hwnd As Long
hwnd = FindWindowA(vbNullString, Me.Caption)
SetWindowLongA hwnd, -16, GetWindowLongA(hwnd, -16) And &HFFF7FFFF
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Dim hwnd As Long
hwnd = FindWindowA(vbNullString, Me.Caption)
SetWindowLongA hwnd, -16, GetWindowLongA(hwnd, -16) Or &H80000
End Sub |
Private Declare Function FindWindowA Lib "USER32" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function GetWindowLongA Lib "USER32" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Private Declare Function SetWindowLongA Lib "USER32" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Private Sub UserForm_Initialize()
Dim hwnd As Long
hwnd = FindWindowA(vbNullString, Me.Caption)
SetWindowLongA hwnd, -16, GetWindowLongA(hwnd, -16) And &HFFF7FFFF
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
Dim hwnd As Long
hwnd = FindWindowA(vbNullString, Me.Caption)
SetWindowLongA hwnd, -16, GetWindowLongA(hwnd, -16) Or &H80000
End Sub
É bom atentar que desaparecer com o botão não desativa o uso do atalho Alt+F4 que fecha a janela.
Bom proveito!
Tomás Vásquez
https://www.tomasvasquez.com.br