How to disable X button in code in visual basic

Viewed 184

I want to disable the X button on a form depending on a condition. So something like:

If Boolean Then 
   ControlBox = False
Else
   ControlBox = True
End If

When I try and use this I get an error message saying visual basic does not support this function. This would be done on the form load and the boolean would not change.

I've searched this forum but can't find an answer to suite me needs.

Thanks in advance.

2 Answers

It looks like you are trying to set the ControlBox property at run-time. As you saw, you cannot do so. However, with a little API magic you can accomplish this task:

Option Explicit

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 SetWindowPos Lib "user32" (ByVal hWnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long

Private Const WS_SYSMENU = &H80000
Private Const GWL_STYLE = (-16)
Private Const SWP_FRAMECHANGED = &H20
Private Const SWP_NOMOVE = &H2
Private Const SWP_NOZORDER = &H4
Private Const SWP_NOSIZE = &H1

Private Property Let ControlBoxVisible(ByVal Value As Boolean)
   Dim style As Long
   
   style = GetWindowLong(Me.hWnd, GWL_STYLE)
   style = IIf(Value, style Or WS_SYSMENU, style And Not WS_SYSMENU)
   SetWindowLong Me.hWnd, GWL_STYLE, style
   SetWindowPos Me.hWnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED Or SWP_NOMOVE Or SWP_NOZORDER Or SWP_NOSIZE
End Property

And then you would use it like this:

Private Sub Form_Load()
   ControlBoxVisible = False
End Sub
Related