|
|
|
 |
How to disable the X close button on
a UserForm
|
Article contributed by
Jonathan West
Sometimes, you don't want to
allow the user to close a UserForm until they have gone through all the steps
you have specified.
Word VBA UserForms don't directly
allow you to disable the Close button, but a little Windows API trickery can get
round this.
Paste the following into the
UserForm's code window for any form where you want the X greyed out and
disabled.
Private Const
MF_BYPOSITION =
&H400
Private Const
MF_REMOVE =
&H1000
Private Declare Function DrawMenuBar
Lib
"user32"
_
(
ByVal
hWnd
As Long
)
As Long
Private Declare Function GetMenuItemCount
Lib
"user32"
_
(
ByVal
hMenu
As Long
)
As Long
Private Declare Function GetSystemMenu
Lib
"user32"
_
(
ByVal
hWnd
As Long
, _
ByVal
bRevert
As Long
)
As Long
Private Declare Function RemoveMenu
Lib
"user32"
_
(
ByVal
hMenu
As Long
, _
ByVal
nPosition
As Long
, _
ByVal
wFlags
As Long
)
As Long
Private Declare Function FindWindow
Lib
"user32"
_
Alias
"FindWindowA"
_
(
ByVal
lpClassName
As String
, _
ByVal
lpWindowName
As String
)
As Long
Private
hWnd
As Long
Private Sub
UserForm_Initialize()
Dim
hMenu
As Long
Dim
menuItemCount
As Long
'Obtain the window handle to the userform
hWnd =
FindWindow
(vbNullString, Me.Caption)
'Obtain the handle to the form's system menu
hMenu =
GetSystemMenu
(hWnd,
0
)
If
hMenu
Then
'Obtain the number of items in the menu
menuItemCount =
GetMenuItemCount
(hMenu)
'Remove the system menu Close menu item.
'The menu item is 0-based, so the last
'item on the menu is menuItemCount - 1
Call RemoveMenu
(hMenu, menuItemCount -
1
, _
MF_REMOVE
Or
MF_BYPOSITION)
'Remove the system menu separator line
Call RemoveMenu
(hMenu, menuItemCount -
2
, _
MF_REMOVE
Or
MF_BYPOSITION)
'Force a redraw of the menu. This
'refreshes the titlebar, dimming the X
Call DrawMenuBar
(hWnd)
End If
End Sub
This code is a VBA adaptation of
a VB6 code sample published by Randy Birch
(Visual Basic MVP) at
http://vbnet.mvps.org/code/forms/killclose.htm. I
would like to thank Randy for permission to use his code in this article.
|